nodes
stringlengths 501
22.4k
| edges
stringlengths 138
5.07k
| code
stringlengths 108
19.3k
|
---|---|---|
0, module; 1, function_definition; 2, function_name:values; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, function_definition; 8, return_statement; 9, comment:"""
Return a list themeables sorted in reverse based
on the their depth in the inheritance hierarchy.
The sorting is key applying and merging the themeables
so that they do not clash i.e :class:`axis_line`
applied before :class:`axis_line_x`.
"""; 10, function_name:key; 11, parameters; 12, block; 13, call; 14, identifier:th; 15, return_statement; 16, identifier:sorted; 17, argument_list; 18, call; 19, call; 20, keyword_argument; 21, keyword_argument; 22, identifier:len; 23, argument_list; 24, attribute; 25, argument_list; 26, identifier:key; 27, identifier:key; 28, identifier:reverse; 29, True; 30, attribute; 31, identifier:dict; 32, identifier:values; 33, identifier:self; 34, attribute; 35, identifier:__mro__; 36, identifier:th; 37, identifier:__class__ | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 6, 9; 7, 10; 7, 11; 7, 12; 8, 13; 11, 14; 12, 15; 13, 16; 13, 17; 15, 18; 17, 19; 17, 20; 17, 21; 18, 22; 18, 23; 19, 24; 19, 25; 20, 26; 20, 27; 21, 28; 21, 29; 23, 30; 24, 31; 24, 32; 25, 33; 30, 34; 30, 35; 34, 36; 34, 37 | def values(self):
"""
Return a list themeables sorted in reverse based
on the their depth in the inheritance hierarchy.
The sorting is key applying and merging the themeables
so that they do not clash i.e :class:`axis_line`
applied before :class:`axis_line_x`.
"""
def key(th):
return len(th.__class__.__mro__)
return sorted(dict.values(self), key=key, reverse=True) |
0, module; 1, function_definition; 2, function_name:topological_sort; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, for_statement; 11, expression_statement; 12, for_statement; 13, expression_statement; 14, while_statement; 15, if_statement; 16, comment:""" Returns a topological ordering of the DAG.
Returns:
list: A list of topologically sorted nodes in the graph.
Raises:
ValueError: Raised if the graph is not acyclic.
"""; 17, assignment; 18, assignment; 19, identifier:u; 20, identifier:graph; 21, block; 22, identifier:u; 23, identifier:graph; 24, block; 25, assignment; 26, identifier:u; 27, identifier:in_degree; 28, block; 29, assignment; 30, identifier:queue; 31, block; 32, comparison_operator:len(sorted_graph) == len(graph); 33, block; 34, else_clause; 35, identifier:graph; 36, attribute; 37, identifier:in_degree; 38, dictionary; 39, expression_statement; 40, for_statement; 41, identifier:queue; 42, call; 43, if_statement; 44, identifier:sorted_graph; 45, list; 46, expression_statement; 47, expression_statement; 48, for_statement; 49, call; 50, call; 51, return_statement; 52, block; 53, identifier:self; 54, identifier:graph; 55, assignment; 56, identifier:v; 57, subscript; 58, block; 59, identifier:deque; 60, argument_list; 61, comparison_operator:in_degree[u] == 0; 62, block; 63, assignment; 64, call; 65, identifier:v; 66, call; 67, block; 68, identifier:len; 69, argument_list; 70, identifier:len; 71, argument_list; 72, identifier:sorted_graph; 73, raise_statement; 74, subscript; 75, integer:0; 76, identifier:graph; 77, identifier:u; 78, expression_statement; 79, subscript; 80, integer:0; 81, expression_statement; 82, identifier:u; 83, call; 84, attribute; 85, argument_list; 86, identifier:sorted; 87, argument_list; 88, expression_statement; 89, if_statement; 90, identifier:sorted_graph; 91, identifier:graph; 92, call; 93, identifier:in_degree; 94, identifier:u; 95, augmented_assignment; 96, identifier:in_degree; 97, identifier:u; 98, call; 99, attribute; 100, argument_list; 101, identifier:sorted_graph; 102, identifier:append; 103, identifier:u; 104, subscript; 105, augmented_assignment; 106, comparison_operator:in_degree[v] == 0; 107, block; 108, identifier:ValueError; 109, argument_list; 110, subscript; 111, integer:1; 112, attribute; 113, argument_list; 114, identifier:queue; 115, identifier:pop; 116, identifier:graph; 117, identifier:u; 118, subscript; 119, integer:1; 120, subscript; 121, integer:0; 122, expression_statement; 123, string; 124, identifier:in_degree; 125, identifier:v; 126, identifier:queue; 127, identifier:appendleft; 128, identifier:u; 129, identifier:in_degree; 130, identifier:v; 131, identifier:in_degree; 132, identifier:v; 133, call; 134, string_content:graph is not acyclic; 135, attribute; 136, argument_list; 137, identifier:queue; 138, identifier:appendleft; 139, identifier:v | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 6, 16; 7, 17; 8, 18; 9, 19; 9, 20; 9, 21; 10, 22; 10, 23; 10, 24; 11, 25; 12, 26; 12, 27; 12, 28; 13, 29; 14, 30; 14, 31; 15, 32; 15, 33; 15, 34; 17, 35; 17, 36; 18, 37; 18, 38; 21, 39; 24, 40; 25, 41; 25, 42; 28, 43; 29, 44; 29, 45; 31, 46; 31, 47; 31, 48; 32, 49; 32, 50; 33, 51; 34, 52; 36, 53; 36, 54; 39, 55; 40, 56; 40, 57; 40, 58; 42, 59; 42, 60; 43, 61; 43, 62; 46, 63; 47, 64; 48, 65; 48, 66; 48, 67; 49, 68; 49, 69; 50, 70; 50, 71; 51, 72; 52, 73; 55, 74; 55, 75; 57, 76; 57, 77; 58, 78; 61, 79; 61, 80; 62, 81; 63, 82; 63, 83; 64, 84; 64, 85; 66, 86; 66, 87; 67, 88; 67, 89; 69, 90; 71, 91; 73, 92; 74, 93; 74, 94; 78, 95; 79, 96; 79, 97; 81, 98; 83, 99; 83, 100; 84, 101; 84, 102; 85, 103; 87, 104; 88, 105; 89, 106; 89, 107; 92, 108; 92, 109; 95, 110; 95, 111; 98, 112; 98, 113; 99, 114; 99, 115; 104, 116; 104, 117; 105, 118; 105, 119; 106, 120; 106, 121; 107, 122; 109, 123; 110, 124; 110, 125; 112, 126; 112, 127; 113, 128; 118, 129; 118, 130; 120, 131; 120, 132; 122, 133; 123, 134; 133, 135; 133, 136; 135, 137; 135, 138; 136, 139 | def topological_sort(self):
""" Returns a topological ordering of the DAG.
Returns:
list: A list of topologically sorted nodes in the graph.
Raises:
ValueError: Raised if the graph is not acyclic.
"""
graph = self.graph
in_degree = {}
for u in graph:
in_degree[u] = 0
for u in graph:
for v in graph[u]:
in_degree[v] += 1
queue = deque()
for u in in_degree:
if in_degree[u] == 0:
queue.appendleft(u)
sorted_graph = []
while queue:
u = queue.pop()
sorted_graph.append(u)
for v in sorted(graph[u]):
in_degree[v] -= 1
if in_degree[v] == 0:
queue.appendleft(v)
if len(sorted_graph) == len(graph):
return sorted_graph
else:
raise ValueError('graph is not acyclic') |
0, module; 1, function_definition; 2, function_name:_music_lib_search; 3, parameters; 4, block; 5, identifier:self; 6, identifier:search; 7, identifier:start; 8, identifier:max_items; 9, expression_statement; 10, expression_statement; 11, comment:# Get result information; 12, expression_statement; 13, for_statement; 14, return_statement; 15, comment:"""Perform a music library search and extract search numbers.
You can get an overview of all the relevant search prefixes (like
'A:') and their meaning with the request:
.. code ::
response = device.contentDirectory.Browse([
('ObjectID', '0'),
('BrowseFlag', 'BrowseDirectChildren'),
('Filter', '*'),
('StartingIndex', 0),
('RequestedCount', 100),
('SortCriteria', '')
])
Args:
search (str): The ID to search.
start (int): The index of the forst item to return.
max_items (int): The maximum number of items to return.
Returns:
tuple: (response, metadata) where response is the returned metadata
and metadata is a dict with the 'number_returned',
'total_matches' and 'update_id' integers
"""; 16, assignment; 17, assignment; 18, identifier:tag; 19, list; 20, block; 21, expression_list; 22, identifier:response; 23, call; 24, identifier:metadata; 25, dictionary; 26, string; 27, string; 28, string; 29, expression_statement; 30, identifier:response; 31, identifier:metadata; 32, attribute; 33, argument_list; 34, string_content:NumberReturned; 35, string_content:TotalMatches; 36, string_content:UpdateID; 37, assignment; 38, attribute; 39, identifier:Browse; 40, list; 41, subscript; 42, call; 43, identifier:self; 44, identifier:contentDirectory; 45, tuple; 46, tuple; 47, tuple; 48, tuple; 49, tuple; 50, tuple; 51, identifier:metadata; 52, call; 53, identifier:int; 54, argument_list; 55, string; 56, identifier:search; 57, string; 58, string; 59, string; 60, string; 61, string; 62, identifier:start; 63, string; 64, identifier:max_items; 65, string; 66, string; 67, identifier:camel_to_underscore; 68, argument_list; 69, subscript; 70, string_content:ObjectID; 71, string_content:BrowseFlag; 72, string_content:BrowseDirectChildren; 73, string_content:Filter; 74, string_content:*; 75, string_content:StartingIndex; 76, string_content:RequestedCount; 77, string_content:SortCriteria; 78, identifier:tag; 79, identifier:response; 80, identifier:tag | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 9, 15; 10, 16; 12, 17; 13, 18; 13, 19; 13, 20; 14, 21; 16, 22; 16, 23; 17, 24; 17, 25; 19, 26; 19, 27; 19, 28; 20, 29; 21, 30; 21, 31; 23, 32; 23, 33; 26, 34; 27, 35; 28, 36; 29, 37; 32, 38; 32, 39; 33, 40; 37, 41; 37, 42; 38, 43; 38, 44; 40, 45; 40, 46; 40, 47; 40, 48; 40, 49; 40, 50; 41, 51; 41, 52; 42, 53; 42, 54; 45, 55; 45, 56; 46, 57; 46, 58; 47, 59; 47, 60; 48, 61; 48, 62; 49, 63; 49, 64; 50, 65; 50, 66; 52, 67; 52, 68; 54, 69; 55, 70; 57, 71; 58, 72; 59, 73; 60, 74; 61, 75; 63, 76; 65, 77; 68, 78; 69, 79; 69, 80 | def _music_lib_search(self, search, start, max_items):
"""Perform a music library search and extract search numbers.
You can get an overview of all the relevant search prefixes (like
'A:') and their meaning with the request:
.. code ::
response = device.contentDirectory.Browse([
('ObjectID', '0'),
('BrowseFlag', 'BrowseDirectChildren'),
('Filter', '*'),
('StartingIndex', 0),
('RequestedCount', 100),
('SortCriteria', '')
])
Args:
search (str): The ID to search.
start (int): The index of the forst item to return.
max_items (int): The maximum number of items to return.
Returns:
tuple: (response, metadata) where response is the returned metadata
and metadata is a dict with the 'number_returned',
'total_matches' and 'update_id' integers
"""
response = self.contentDirectory.Browse([
('ObjectID', search),
('BrowseFlag', 'BrowseDirectChildren'),
('Filter', '*'),
('StartingIndex', start),
('RequestedCount', max_items),
('SortCriteria', '')
])
# Get result information
metadata = {}
for tag in ['NumberReturned', 'TotalMatches', 'UpdateID']:
metadata[camel_to_underscore(tag)] = int(response[tag])
return response, metadata |
0, module; 1, function_definition; 2, function_name:unique; 3, parameters; 4, block; 5, identifier:seq; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""Return the unique elements of a collection even if those elements are
unhashable and unsortable, like dicts and sets"""; 11, assignment; 12, identifier:each; 13, identifier:seq; 14, block; 15, identifier:cleaned; 16, identifier:cleaned; 17, list; 18, if_statement; 19, comparison_operator:each not in cleaned; 20, block; 21, identifier:each; 22, identifier:cleaned; 23, expression_statement; 24, call; 25, attribute; 26, argument_list; 27, identifier:cleaned; 28, identifier:append; 29, identifier:each | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 9, 15; 11, 16; 11, 17; 14, 18; 18, 19; 18, 20; 19, 21; 19, 22; 20, 23; 23, 24; 24, 25; 24, 26; 25, 27; 25, 28; 26, 29 | def unique(seq):
"""Return the unique elements of a collection even if those elements are
unhashable and unsortable, like dicts and sets"""
cleaned = []
for each in seq:
if each not in cleaned:
cleaned.append(each)
return cleaned |
0, module; 1, function_definition; 2, function_name:build_schema_info; 3, parameters; 4, block; 5, identifier:connection_alias; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, with_statement; 10, return_statement; 11, comment:"""
Construct schema information via engine-specific queries of the tables in the DB.
:return: Schema information of the following form, sorted by db_table_name.
[
("db_table_name",
[
("db_column_name", "DbFieldType"),
(...),
]
)
]
"""; 12, assignment; 13, assignment; 14, with_clause; 15, block; 16, identifier:ret; 17, identifier:connection; 18, call; 19, identifier:ret; 20, list; 21, with_item; 22, expression_statement; 23, for_statement; 24, identifier:get_valid_connection; 25, argument_list; 26, as_pattern; 27, assignment; 28, identifier:table_name; 29, identifier:tables_to_introspect; 30, block; 31, identifier:connection_alias; 32, call; 33, as_pattern_target; 34, identifier:tables_to_introspect; 35, call; 36, if_statement; 37, expression_statement; 38, expression_statement; 39, for_statement; 40, expression_statement; 41, attribute; 42, argument_list; 43, identifier:cursor; 44, attribute; 45, argument_list; 46, not_operator; 47, block; 48, assignment; 49, assignment; 50, identifier:row; 51, identifier:table_description; 52, block; 53, call; 54, identifier:connection; 55, identifier:cursor; 56, attribute; 57, identifier:table_names; 58, identifier:cursor; 59, keyword_argument; 60, call; 61, continue_statement; 62, identifier:td; 63, list; 64, identifier:table_description; 65, call; 66, expression_statement; 67, try_statement; 68, expression_statement; 69, attribute; 70, argument_list; 71, identifier:connection; 72, identifier:introspection; 73, identifier:include_views; 74, call; 75, identifier:_include_table; 76, argument_list; 77, attribute; 78, argument_list; 79, assignment; 80, block; 81, except_clause; 82, call; 83, identifier:ret; 84, identifier:append; 85, tuple; 86, identifier:_include_views; 87, argument_list; 88, identifier:table_name; 89, attribute; 90, identifier:get_table_description; 91, identifier:cursor; 92, identifier:table_name; 93, identifier:column_name; 94, subscript; 95, expression_statement; 96, as_pattern; 97, block; 98, attribute; 99, argument_list; 100, identifier:table_name; 101, identifier:td; 102, identifier:connection; 103, identifier:introspection; 104, identifier:row; 105, integer:0; 106, assignment; 107, identifier:KeyError; 108, as_pattern_target; 109, expression_statement; 110, identifier:td; 111, identifier:append; 112, tuple; 113, identifier:field_type; 114, call; 115, identifier:e; 116, assignment; 117, identifier:column_name; 118, identifier:field_type; 119, attribute; 120, argument_list; 121, identifier:field_type; 122, string; 123, attribute; 124, identifier:get_field_type; 125, subscript; 126, identifier:row; 127, string_content:Unknown; 128, identifier:connection; 129, identifier:introspection; 130, identifier:row; 131, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 8, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 13, 19; 13, 20; 14, 21; 15, 22; 15, 23; 18, 24; 18, 25; 21, 26; 22, 27; 23, 28; 23, 29; 23, 30; 25, 31; 26, 32; 26, 33; 27, 34; 27, 35; 30, 36; 30, 37; 30, 38; 30, 39; 30, 40; 32, 41; 32, 42; 33, 43; 35, 44; 35, 45; 36, 46; 36, 47; 37, 48; 38, 49; 39, 50; 39, 51; 39, 52; 40, 53; 41, 54; 41, 55; 44, 56; 44, 57; 45, 58; 45, 59; 46, 60; 47, 61; 48, 62; 48, 63; 49, 64; 49, 65; 52, 66; 52, 67; 52, 68; 53, 69; 53, 70; 56, 71; 56, 72; 59, 73; 59, 74; 60, 75; 60, 76; 65, 77; 65, 78; 66, 79; 67, 80; 67, 81; 68, 82; 69, 83; 69, 84; 70, 85; 74, 86; 74, 87; 76, 88; 77, 89; 77, 90; 78, 91; 78, 92; 79, 93; 79, 94; 80, 95; 81, 96; 81, 97; 82, 98; 82, 99; 85, 100; 85, 101; 89, 102; 89, 103; 94, 104; 94, 105; 95, 106; 96, 107; 96, 108; 97, 109; 98, 110; 98, 111; 99, 112; 106, 113; 106, 114; 108, 115; 109, 116; 112, 117; 112, 118; 114, 119; 114, 120; 116, 121; 116, 122; 119, 123; 119, 124; 120, 125; 120, 126; 122, 127; 123, 128; 123, 129; 125, 130; 125, 131 | def build_schema_info(connection_alias):
"""
Construct schema information via engine-specific queries of the tables in the DB.
:return: Schema information of the following form, sorted by db_table_name.
[
("db_table_name",
[
("db_column_name", "DbFieldType"),
(...),
]
)
]
"""
connection = get_valid_connection(connection_alias)
ret = []
with connection.cursor() as cursor:
tables_to_introspect = connection.introspection.table_names(cursor, include_views=_include_views())
for table_name in tables_to_introspect:
if not _include_table(table_name):
continue
td = []
table_description = connection.introspection.get_table_description(cursor, table_name)
for row in table_description:
column_name = row[0]
try:
field_type = connection.introspection.get_field_type(row[1], row)
except KeyError as e:
field_type = 'Unknown'
td.append((column_name, field_type))
ret.append((table_name, td))
return ret |
0, module; 1, function_definition; 2, function_name:fetchThreads; 3, parameters; 4, block; 5, identifier:self; 6, identifier:thread_location; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, while_statement; 14, comment:# Return only threads between before and after (if set); 15, if_statement; 16, if_statement; 17, return_statement; 18, identifier:before; 19, None; 20, identifier:after; 21, None; 22, identifier:limit; 23, None; 24, comment:"""
Get all threads in thread_location.
Threads will be sorted from newest to oldest.
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: Fetch only thread before this epoch (in ms) (default all threads)
:param after: Fetch only thread after this epoch (in ms) (default all threads)
:param limit: The max. amount of threads to fetch (default all threads)
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed
"""; 25, assignment; 26, assignment; 27, True; 28, comment:# break if limit is exceeded; 29, block; 30, boolean_operator; 31, block; 32, boolean_operator; 33, block; 34, identifier:threads; 35, identifier:threads; 36, list; 37, identifier:last_thread_timestamp; 38, None; 39, if_statement; 40, comment:# fetchThreadList returns at max 20 threads before last_thread_timestamp (included); 41, expression_statement; 42, if_statement; 43, expression_statement; 44, comment:# FB returns a sorted list of threads; 45, if_statement; 46, comparison_operator:before is not None; 47, comparison_operator:after is not None; 48, for_statement; 49, identifier:limit; 50, comparison_operator:len(threads) > limit; 51, return_statement; 52, boolean_operator; 53, block; 54, assignment; 55, comparison_operator:len(candidates) > 1; 56, block; 57, else_clause; 58, assignment; 59, boolean_operator; 60, block; 61, identifier:before; 62, None; 63, identifier:after; 64, None; 65, identifier:t; 66, identifier:threads; 67, block; 68, call; 69, identifier:limit; 70, subscript; 71, identifier:limit; 72, comparison_operator:len(threads) >= limit; 73, break_statement; 74, identifier:candidates; 75, call; 76, call; 77, integer:1; 78, expression_statement; 79, comment:# End of threads; 80, block; 81, identifier:last_thread_timestamp; 82, attribute; 83, parenthesized_expression; 84, parenthesized_expression; 85, break_statement; 86, expression_statement; 87, if_statement; 88, identifier:len; 89, argument_list; 90, identifier:threads; 91, slice; 92, call; 93, identifier:limit; 94, attribute; 95, argument_list; 96, identifier:len; 97, argument_list; 98, augmented_assignment; 99, break_statement; 100, subscript; 101, identifier:last_message_timestamp; 102, boolean_operator; 103, boolean_operator; 104, assignment; 105, boolean_operator; 106, block; 107, identifier:threads; 108, identifier:limit; 109, identifier:len; 110, argument_list; 111, identifier:self; 112, identifier:fetchThreadList; 113, keyword_argument; 114, keyword_argument; 115, identifier:candidates; 116, identifier:threads; 117, subscript; 118, identifier:threads; 119, unary_operator; 120, comparison_operator:before is not None; 121, comparison_operator:int(last_thread_timestamp) > before; 122, comparison_operator:after is not None; 123, comparison_operator:int(last_thread_timestamp) < after; 124, identifier:last_message_timestamp; 125, call; 126, parenthesized_expression; 127, parenthesized_expression; 128, expression_statement; 129, identifier:threads; 130, identifier:before; 131, identifier:last_thread_timestamp; 132, identifier:thread_location; 133, identifier:thread_location; 134, identifier:candidates; 135, slice; 136, integer:1; 137, identifier:before; 138, None; 139, call; 140, identifier:before; 141, identifier:after; 142, None; 143, call; 144, identifier:after; 145, identifier:int; 146, argument_list; 147, boolean_operator; 148, boolean_operator; 149, call; 150, integer:1; 151, identifier:int; 152, argument_list; 153, identifier:int; 154, argument_list; 155, attribute; 156, comparison_operator:before is not None; 157, comparison_operator:last_message_timestamp > before; 158, comparison_operator:after is not None; 159, comparison_operator:last_message_timestamp < after; 160, attribute; 161, argument_list; 162, identifier:last_thread_timestamp; 163, identifier:last_thread_timestamp; 164, identifier:t; 165, identifier:last_message_timestamp; 166, identifier:before; 167, None; 168, identifier:last_message_timestamp; 169, identifier:before; 170, identifier:after; 171, None; 172, identifier:last_message_timestamp; 173, identifier:after; 174, identifier:threads; 175, identifier:remove; 176, identifier:t | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 7, 18; 7, 19; 8, 20; 8, 21; 9, 22; 9, 23; 10, 24; 11, 25; 12, 26; 13, 27; 13, 28; 13, 29; 15, 30; 15, 31; 16, 32; 16, 33; 17, 34; 25, 35; 25, 36; 26, 37; 26, 38; 29, 39; 29, 40; 29, 41; 29, 42; 29, 43; 29, 44; 29, 45; 30, 46; 30, 47; 31, 48; 32, 49; 32, 50; 33, 51; 39, 52; 39, 53; 41, 54; 42, 55; 42, 56; 42, 57; 43, 58; 45, 59; 45, 60; 46, 61; 46, 62; 47, 63; 47, 64; 48, 65; 48, 66; 48, 67; 50, 68; 50, 69; 51, 70; 52, 71; 52, 72; 53, 73; 54, 74; 54, 75; 55, 76; 55, 77; 56, 78; 57, 79; 57, 80; 58, 81; 58, 82; 59, 83; 59, 84; 60, 85; 67, 86; 67, 87; 68, 88; 68, 89; 70, 90; 70, 91; 72, 92; 72, 93; 75, 94; 75, 95; 76, 96; 76, 97; 78, 98; 80, 99; 82, 100; 82, 101; 83, 102; 84, 103; 86, 104; 87, 105; 87, 106; 89, 107; 91, 108; 92, 109; 92, 110; 94, 111; 94, 112; 95, 113; 95, 114; 97, 115; 98, 116; 98, 117; 100, 118; 100, 119; 102, 120; 102, 121; 103, 122; 103, 123; 104, 124; 104, 125; 105, 126; 105, 127; 106, 128; 110, 129; 113, 130; 113, 131; 114, 132; 114, 133; 117, 134; 117, 135; 119, 136; 120, 137; 120, 138; 121, 139; 121, 140; 122, 141; 122, 142; 123, 143; 123, 144; 125, 145; 125, 146; 126, 147; 127, 148; 128, 149; 135, 150; 139, 151; 139, 152; 143, 153; 143, 154; 146, 155; 147, 156; 147, 157; 148, 158; 148, 159; 149, 160; 149, 161; 152, 162; 154, 163; 155, 164; 155, 165; 156, 166; 156, 167; 157, 168; 157, 169; 158, 170; 158, 171; 159, 172; 159, 173; 160, 174; 160, 175; 161, 176 | def fetchThreads(self, thread_location, before=None, after=None, limit=None):
"""
Get all threads in thread_location.
Threads will be sorted from newest to oldest.
:param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER
:param before: Fetch only thread before this epoch (in ms) (default all threads)
:param after: Fetch only thread after this epoch (in ms) (default all threads)
:param limit: The max. amount of threads to fetch (default all threads)
:return: :class:`models.Thread` objects
:rtype: list
:raises: FBchatException if request failed
"""
threads = []
last_thread_timestamp = None
while True:
# break if limit is exceeded
if limit and len(threads) >= limit:
break
# fetchThreadList returns at max 20 threads before last_thread_timestamp (included)
candidates = self.fetchThreadList(
before=last_thread_timestamp, thread_location=thread_location
)
if len(candidates) > 1:
threads += candidates[1:]
else: # End of threads
break
last_thread_timestamp = threads[-1].last_message_timestamp
# FB returns a sorted list of threads
if (before is not None and int(last_thread_timestamp) > before) or (
after is not None and int(last_thread_timestamp) < after
):
break
# Return only threads between before and after (if set)
if before is not None or after is not None:
for t in threads:
last_message_timestamp = int(t.last_message_timestamp)
if (before is not None and last_message_timestamp > before) or (
after is not None and last_message_timestamp < after
):
threads.remove(t)
if limit and len(threads) > limit:
return threads[:limit]
return threads |
0, module; 1, function_definition; 2, function_name:_get_key_value; 3, parameters; 4, block; 5, identifier:self; 6, identifier:key; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, identifier:is_hll; 11, False; 12, string; 13, identifier:is_hll; 14, comment:# get hll value; 15, block; 16, else_clause; 17, string_content:Returns the proper key value for the stats
@param key: the redis key
@param is_hll: the key is a HyperLogLog, else is a sorted set; 18, return_statement; 19, comment:# get zcard value; 20, block; 21, call; 22, return_statement; 23, attribute; 24, argument_list; 25, call; 26, attribute; 27, identifier:execute_command; 28, string:"PFCOUNT"; 29, identifier:key; 30, attribute; 31, argument_list; 32, identifier:self; 33, identifier:redis_conn; 34, attribute; 35, identifier:zcard; 36, identifier:key; 37, identifier:self; 38, identifier:redis_conn | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 7, 10; 7, 11; 8, 12; 9, 13; 9, 14; 9, 15; 9, 16; 12, 17; 15, 18; 16, 19; 16, 20; 18, 21; 20, 22; 21, 23; 21, 24; 22, 25; 23, 26; 23, 27; 24, 28; 24, 29; 25, 30; 25, 31; 26, 32; 26, 33; 30, 34; 30, 35; 31, 36; 34, 37; 34, 38 | def _get_key_value(self, key, is_hll=False):
'''
Returns the proper key value for the stats
@param key: the redis key
@param is_hll: the key is a HyperLogLog, else is a sorted set
'''
if is_hll:
# get hll value
return self.redis_conn.execute_command("PFCOUNT", key)
else:
# get zcard value
return self.redis_conn.zcard(key) |
0, module; 1, function_definition; 2, function_name:_get_bin; 3, parameters; 4, block; 5, identifier:self; 6, identifier:key; 7, expression_statement; 8, comment:# keys based on score; 9, expression_statement; 10, comment:# this doesnt return them in order, need to bin first; 11, for_statement; 12, return_statement; 13, string; 14, assignment; 15, identifier:item; 16, call; 17, block; 18, identifier:sortedDict; 19, string_content:Returns a binned dictionary based on redis zscore
@return: The sorted dict; 20, identifier:sortedDict; 21, dictionary; 22, attribute; 23, argument_list; 24, expression_statement; 25, comment:# score is negated in redis; 26, expression_statement; 27, if_statement; 28, expression_statement; 29, attribute; 30, identifier:zscan_iter; 31, identifier:key; 32, assignment; 33, assignment; 34, comparison_operator:my_score not in sortedDict; 35, block; 36, call; 37, identifier:self; 38, identifier:redis_conn; 39, identifier:my_item; 40, call; 41, identifier:my_score; 42, unary_operator; 43, identifier:my_score; 44, identifier:sortedDict; 45, expression_statement; 46, attribute; 47, argument_list; 48, attribute; 49, argument_list; 50, subscript; 51, assignment; 52, subscript; 53, identifier:append; 54, identifier:my_item; 55, identifier:ujson; 56, identifier:loads; 57, subscript; 58, identifier:item; 59, integer:1; 60, subscript; 61, list; 62, identifier:sortedDict; 63, identifier:my_score; 64, identifier:item; 65, integer:0; 66, identifier:sortedDict; 67, identifier:my_score | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 9, 14; 11, 15; 11, 16; 11, 17; 12, 18; 13, 19; 14, 20; 14, 21; 16, 22; 16, 23; 17, 24; 17, 25; 17, 26; 17, 27; 17, 28; 22, 29; 22, 30; 23, 31; 24, 32; 26, 33; 27, 34; 27, 35; 28, 36; 29, 37; 29, 38; 32, 39; 32, 40; 33, 41; 33, 42; 34, 43; 34, 44; 35, 45; 36, 46; 36, 47; 40, 48; 40, 49; 42, 50; 45, 51; 46, 52; 46, 53; 47, 54; 48, 55; 48, 56; 49, 57; 50, 58; 50, 59; 51, 60; 51, 61; 52, 62; 52, 63; 57, 64; 57, 65; 60, 66; 60, 67 | def _get_bin(self, key):
'''
Returns a binned dictionary based on redis zscore
@return: The sorted dict
'''
# keys based on score
sortedDict = {}
# this doesnt return them in order, need to bin first
for item in self.redis_conn.zscan_iter(key):
my_item = ujson.loads(item[0])
# score is negated in redis
my_score = -item[1]
if my_score not in sortedDict:
sortedDict[my_score] = []
sortedDict[my_score].append(my_item)
return sortedDict |
0, module; 1, function_definition; 2, function_name:_is_viable_phone_number; 3, parameters; 4, block; 5, identifier:number; 6, expression_statement; 7, if_statement; 8, expression_statement; 9, return_statement; 10, comment:"""Checks to see if a string could possibly be a phone number.
At the moment, checks to see that the string begins with at least 2
digits, ignoring any punctuation commonly found in phone numbers. This
method does not require the number to be normalized in advance - but does
assume that leading non-number symbols have been removed, such as by the
method _extract_possible_number.
Arguments:
number -- string to be checked for viability as a phone number
Returns True if the number could be a phone number of some sort, otherwise
False
"""; 11, comparison_operator:len(number) < _MIN_LENGTH_FOR_NSN; 12, block; 13, assignment; 14, call; 15, call; 16, identifier:_MIN_LENGTH_FOR_NSN; 17, return_statement; 18, identifier:match; 19, call; 20, identifier:bool; 21, argument_list; 22, identifier:len; 23, argument_list; 24, False; 25, identifier:fullmatch; 26, argument_list; 27, identifier:match; 28, identifier:number; 29, identifier:_VALID_PHONE_NUMBER_PATTERN; 30, identifier:number | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 7, 12; 8, 13; 9, 14; 11, 15; 11, 16; 12, 17; 13, 18; 13, 19; 14, 20; 14, 21; 15, 22; 15, 23; 17, 24; 19, 25; 19, 26; 21, 27; 23, 28; 26, 29; 26, 30 | def _is_viable_phone_number(number):
"""Checks to see if a string could possibly be a phone number.
At the moment, checks to see that the string begins with at least 2
digits, ignoring any punctuation commonly found in phone numbers. This
method does not require the number to be normalized in advance - but does
assume that leading non-number symbols have been removed, such as by the
method _extract_possible_number.
Arguments:
number -- string to be checked for viability as a phone number
Returns True if the number could be a phone number of some sort, otherwise
False
"""
if len(number) < _MIN_LENGTH_FOR_NSN:
return False
match = fullmatch(_VALID_PHONE_NUMBER_PATTERN, number)
return bool(match) |
0, module; 1, function_definition; 2, function_name:__encoded_params_for_signature; 3, parameters; 4, block; 5, identifier:cls; 6, identifier:params; 7, expression_statement; 8, function_definition; 9, return_statement; 10, comment:"""
Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&'
"""; 11, function_name:encoded_pairs; 12, parameters; 13, block; 14, call; 15, identifier:params; 16, for_statement; 17, attribute; 18, argument_list; 19, pattern_list; 20, call; 21, block; 22, string:"&"; 23, identifier:join; 24, call; 25, identifier:k; 26, identifier:v; 27, attribute; 28, argument_list; 29, if_statement; 30, if_statement; 31, comment:# escape delimiters to avoid tampering; 32, expression_statement; 33, expression_statement; 34, expression_statement; 35, identifier:sorted; 36, argument_list; 37, identifier:six; 38, identifier:iteritems; 39, identifier:params; 40, comparison_operator:k == 'hmac'; 41, block; 42, call; 43, comment:#foo[]=1&foo[]=2 has to be transformed as foo=["1", "2"] note the whitespace after comma; 44, block; 45, assignment; 46, assignment; 47, yield; 48, call; 49, identifier:k; 50, string; 51, continue_statement; 52, attribute; 53, argument_list; 54, expression_statement; 55, expression_statement; 56, identifier:k; 57, call; 58, identifier:v; 59, call; 60, call; 61, identifier:encoded_pairs; 62, argument_list; 63, string_content:hmac; 64, identifier:k; 65, identifier:endswith; 66, string; 67, assignment; 68, assignment; 69, attribute; 70, argument_list; 71, attribute; 72, argument_list; 73, attribute; 74, argument_list; 75, identifier:params; 76, string_content:[]; 77, identifier:k; 78, call; 79, identifier:v; 80, call; 81, call; 82, identifier:replace; 83, string:"="; 84, string:"%3D"; 85, call; 86, identifier:replace; 87, string:"%"; 88, string:"%25"; 89, call; 90, identifier:replace; 91, string:"&"; 92, string:"%26"; 93, attribute; 94, argument_list; 95, attribute; 96, argument_list; 97, attribute; 98, argument_list; 99, identifier:str; 100, argument_list; 101, attribute; 102, argument_list; 103, identifier:k; 104, identifier:rstrip; 105, string; 106, identifier:json; 107, identifier:dumps; 108, call; 109, call; 110, identifier:replace; 111, string:"%"; 112, string:"%25"; 113, identifier:v; 114, string; 115, identifier:format; 116, identifier:k; 117, identifier:v; 118, string_content:[]; 119, identifier:list; 120, argument_list; 121, identifier:str; 122, argument_list; 123, string_content:{0}={1}; 124, call; 125, identifier:k; 126, identifier:map; 127, argument_list; 128, identifier:str; 129, identifier:v | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 8, 12; 8, 13; 9, 14; 12, 15; 13, 16; 14, 17; 14, 18; 16, 19; 16, 20; 16, 21; 17, 22; 17, 23; 18, 24; 19, 25; 19, 26; 20, 27; 20, 28; 21, 29; 21, 30; 21, 31; 21, 32; 21, 33; 21, 34; 24, 35; 24, 36; 27, 37; 27, 38; 28, 39; 29, 40; 29, 41; 30, 42; 30, 43; 30, 44; 32, 45; 33, 46; 34, 47; 36, 48; 40, 49; 40, 50; 41, 51; 42, 52; 42, 53; 44, 54; 44, 55; 45, 56; 45, 57; 46, 58; 46, 59; 47, 60; 48, 61; 48, 62; 50, 63; 52, 64; 52, 65; 53, 66; 54, 67; 55, 68; 57, 69; 57, 70; 59, 71; 59, 72; 60, 73; 60, 74; 62, 75; 66, 76; 67, 77; 67, 78; 68, 79; 68, 80; 69, 81; 69, 82; 70, 83; 70, 84; 71, 85; 71, 86; 72, 87; 72, 88; 73, 89; 73, 90; 74, 91; 74, 92; 78, 93; 78, 94; 80, 95; 80, 96; 81, 97; 81, 98; 85, 99; 85, 100; 89, 101; 89, 102; 93, 103; 93, 104; 94, 105; 95, 106; 95, 107; 96, 108; 97, 109; 97, 110; 98, 111; 98, 112; 100, 113; 101, 114; 101, 115; 102, 116; 102, 117; 105, 118; 108, 119; 108, 120; 109, 121; 109, 122; 114, 123; 120, 124; 122, 125; 124, 126; 124, 127; 127, 128; 127, 129 | def __encoded_params_for_signature(cls, params):
"""
Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&'
"""
def encoded_pairs(params):
for k, v in six.iteritems(params):
if k == 'hmac':
continue
if k.endswith('[]'):
#foo[]=1&foo[]=2 has to be transformed as foo=["1", "2"] note the whitespace after comma
k = k.rstrip('[]')
v = json.dumps(list(map(str, v)))
# escape delimiters to avoid tampering
k = str(k).replace("%", "%25").replace("=", "%3D")
v = str(v).replace("%", "%25")
yield '{0}={1}'.format(k, v).replace("&", "%26")
return "&".join(sorted(encoded_pairs(params))) |
0, module; 1, function_definition; 2, function_name:group_keys; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, for_statement; 8, comment:"""Return an iterator over member names for groups only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.group_keys())
['bar', 'foo']
"""; 9, identifier:key; 10, call; 11, block; 12, identifier:sorted; 13, argument_list; 14, expression_statement; 15, if_statement; 16, call; 17, assignment; 18, call; 19, block; 20, identifier:listdir; 21, argument_list; 22, identifier:path; 23, binary_operator:self._key_prefix + key; 24, identifier:contains_group; 25, argument_list; 26, expression_statement; 27, attribute; 28, attribute; 29, attribute; 30, identifier:key; 31, attribute; 32, identifier:path; 33, yield; 34, identifier:self; 35, identifier:_store; 36, identifier:self; 37, identifier:_path; 38, identifier:self; 39, identifier:_key_prefix; 40, identifier:self; 41, identifier:_store; 42, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 7, 10; 7, 11; 10, 12; 10, 13; 11, 14; 11, 15; 13, 16; 14, 17; 15, 18; 15, 19; 16, 20; 16, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 21, 27; 21, 28; 23, 29; 23, 30; 25, 31; 25, 32; 26, 33; 27, 34; 27, 35; 28, 36; 28, 37; 29, 38; 29, 39; 31, 40; 31, 41; 33, 42 | def group_keys(self):
"""Return an iterator over member names for groups only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.group_keys())
['bar', 'foo']
"""
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_group(self._store, path):
yield key |
0, module; 1, function_definition; 2, function_name:array_keys; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, for_statement; 8, comment:"""Return an iterator over member names for arrays only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.array_keys())
['baz', 'quux']
"""; 9, identifier:key; 10, call; 11, block; 12, identifier:sorted; 13, argument_list; 14, expression_statement; 15, if_statement; 16, call; 17, assignment; 18, call; 19, block; 20, identifier:listdir; 21, argument_list; 22, identifier:path; 23, binary_operator:self._key_prefix + key; 24, identifier:contains_array; 25, argument_list; 26, expression_statement; 27, attribute; 28, attribute; 29, attribute; 30, identifier:key; 31, attribute; 32, identifier:path; 33, yield; 34, identifier:self; 35, identifier:_store; 36, identifier:self; 37, identifier:_path; 38, identifier:self; 39, identifier:_key_prefix; 40, identifier:self; 41, identifier:_store; 42, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 7, 10; 7, 11; 10, 12; 10, 13; 11, 14; 11, 15; 13, 16; 14, 17; 15, 18; 15, 19; 16, 20; 16, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 21, 27; 21, 28; 23, 29; 23, 30; 25, 31; 25, 32; 26, 33; 27, 34; 27, 35; 28, 36; 28, 37; 29, 38; 29, 39; 31, 40; 31, 41; 33, 42 | def array_keys(self):
"""Return an iterator over member names for arrays only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.array_keys())
['baz', 'quux']
"""
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_array(self._store, path):
yield key |
0, module; 1, function_definition; 2, function_name:init_array; 3, parameters; 4, block; 5, identifier:store; 6, identifier:shape; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, default_parameter; 14, default_parameter; 15, default_parameter; 16, default_parameter; 17, expression_statement; 18, comment:# normalize path; 19, expression_statement; 20, comment:# ensure parent group initialized; 21, expression_statement; 22, expression_statement; 23, identifier:chunks; 24, True; 25, identifier:dtype; 26, None; 27, identifier:compressor; 28, string; 29, identifier:fill_value; 30, None; 31, identifier:order; 32, string; 33, identifier:overwrite; 34, False; 35, identifier:path; 36, None; 37, identifier:chunk_store; 38, None; 39, identifier:filters; 40, None; 41, identifier:object_codec; 42, None; 43, comment:"""Initialize an array store with the given configuration. Note that this is a low-level
function and there should be no need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and bytes-like values.
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape. If True, will be guessed from `shape` and `dtype`. If
False, will be set to `shape`, i.e., single chunk for the whole array.
dtype : string or dtype, optional
NumPy dtype.
compressor : Codec, optional
Primary compressor.
fill_value : object
Default value to use for uninitialized portions of the array.
order : {'C', 'F'}, optional
Memory layout to be used within each chunk.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, optional
Path under which array is stored.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to compression.
object_codec : Codec, optional
A codec to encode object arrays, only needed if dtype=object.
Examples
--------
Initialize an array store::
>>> from zarr.storage import init_array
>>> store = dict()
>>> init_array(store, shape=(10000, 10000), chunks=(1000, 1000))
>>> sorted(store.keys())
['.zarray']
Array metadata is stored as JSON::
>>> print(store['.zarray'].decode())
{
"chunks": [
1000,
1000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "<f8",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
10000,
10000
],
"zarr_format": 2
}
Initialize an array using a storage path::
>>> store = dict()
>>> init_array(store, shape=100000000, chunks=1000000, dtype='i1', path='foo')
>>> sorted(store.keys())
['.zgroup', 'foo/.zarray']
>>> print(store['foo/.zarray'].decode())
{
"chunks": [
1000000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "|i1",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
100000000
],
"zarr_format": 2
}
Notes
-----
The initialisation process involves normalising all array metadata, encoding
as JSON and storing under the '.zarray' key.
"""; 44, assignment; 45, call; 46, call; 47, string_content:default; 48, string_content:C; 49, identifier:path; 50, call; 51, identifier:_require_parent_group; 52, argument_list; 53, identifier:_init_array_metadata; 54, argument_list; 55, identifier:normalize_storage_path; 56, argument_list; 57, identifier:path; 58, keyword_argument; 59, keyword_argument; 60, keyword_argument; 61, identifier:store; 62, keyword_argument; 63, keyword_argument; 64, keyword_argument; 65, keyword_argument; 66, keyword_argument; 67, keyword_argument; 68, keyword_argument; 69, keyword_argument; 70, keyword_argument; 71, keyword_argument; 72, keyword_argument; 73, identifier:path; 74, identifier:store; 75, identifier:store; 76, identifier:chunk_store; 77, identifier:chunk_store; 78, identifier:overwrite; 79, identifier:overwrite; 80, identifier:shape; 81, identifier:shape; 82, identifier:chunks; 83, identifier:chunks; 84, identifier:dtype; 85, identifier:dtype; 86, identifier:compressor; 87, identifier:compressor; 88, identifier:fill_value; 89, identifier:fill_value; 90, identifier:order; 91, identifier:order; 92, identifier:overwrite; 93, identifier:overwrite; 94, identifier:path; 95, identifier:path; 96, identifier:chunk_store; 97, identifier:chunk_store; 98, identifier:filters; 99, identifier:filters; 100, identifier:object_codec; 101, identifier:object_codec | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 3, 14; 3, 15; 3, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 7, 23; 7, 24; 8, 25; 8, 26; 9, 27; 9, 28; 10, 29; 10, 30; 11, 31; 11, 32; 12, 33; 12, 34; 13, 35; 13, 36; 14, 37; 14, 38; 15, 39; 15, 40; 16, 41; 16, 42; 17, 43; 19, 44; 21, 45; 22, 46; 28, 47; 32, 48; 44, 49; 44, 50; 45, 51; 45, 52; 46, 53; 46, 54; 50, 55; 50, 56; 52, 57; 52, 58; 52, 59; 52, 60; 54, 61; 54, 62; 54, 63; 54, 64; 54, 65; 54, 66; 54, 67; 54, 68; 54, 69; 54, 70; 54, 71; 54, 72; 56, 73; 58, 74; 58, 75; 59, 76; 59, 77; 60, 78; 60, 79; 62, 80; 62, 81; 63, 82; 63, 83; 64, 84; 64, 85; 65, 86; 65, 87; 66, 88; 66, 89; 67, 90; 67, 91; 68, 92; 68, 93; 69, 94; 69, 95; 70, 96; 70, 97; 71, 98; 71, 99; 72, 100; 72, 101 | def init_array(store, shape, chunks=True, dtype=None, compressor='default',
fill_value=None, order='C', overwrite=False, path=None,
chunk_store=None, filters=None, object_codec=None):
"""Initialize an array store with the given configuration. Note that this is a low-level
function and there should be no need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and bytes-like values.
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape. If True, will be guessed from `shape` and `dtype`. If
False, will be set to `shape`, i.e., single chunk for the whole array.
dtype : string or dtype, optional
NumPy dtype.
compressor : Codec, optional
Primary compressor.
fill_value : object
Default value to use for uninitialized portions of the array.
order : {'C', 'F'}, optional
Memory layout to be used within each chunk.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, optional
Path under which array is stored.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to compression.
object_codec : Codec, optional
A codec to encode object arrays, only needed if dtype=object.
Examples
--------
Initialize an array store::
>>> from zarr.storage import init_array
>>> store = dict()
>>> init_array(store, shape=(10000, 10000), chunks=(1000, 1000))
>>> sorted(store.keys())
['.zarray']
Array metadata is stored as JSON::
>>> print(store['.zarray'].decode())
{
"chunks": [
1000,
1000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "<f8",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
10000,
10000
],
"zarr_format": 2
}
Initialize an array using a storage path::
>>> store = dict()
>>> init_array(store, shape=100000000, chunks=1000000, dtype='i1', path='foo')
>>> sorted(store.keys())
['.zgroup', 'foo/.zarray']
>>> print(store['foo/.zarray'].decode())
{
"chunks": [
1000000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "|i1",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
100000000
],
"zarr_format": 2
}
Notes
-----
The initialisation process involves normalising all array metadata, encoding
as JSON and storing under the '.zarray' key.
"""
# normalize path
path = normalize_storage_path(path)
# ensure parent group initialized
_require_parent_group(path, store=store, chunk_store=chunk_store, overwrite=overwrite)
_init_array_metadata(store, shape=shape, chunks=chunks, dtype=dtype,
compressor=compressor, fill_value=fill_value,
order=order, overwrite=overwrite, path=path,
chunk_store=chunk_store, filters=filters,
object_codec=object_codec) |
0, module; 1, function_definition; 2, function_name:view; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, if_statement; 18, if_statement; 19, expression_statement; 20, expression_statement; 21, comment:# allow override of some properties; 22, if_statement; 23, if_statement; 24, if_statement; 25, if_statement; 26, if_statement; 27, return_statement; 28, identifier:shape; 29, None; 30, identifier:chunks; 31, None; 32, identifier:dtype; 33, None; 34, identifier:fill_value; 35, None; 36, identifier:filters; 37, None; 38, identifier:read_only; 39, None; 40, identifier:synchronizer; 41, None; 42, comment:"""Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape.
dtype : string or dtype, optional
NumPy dtype.
fill_value : object
Default value to use for uninitialized portions of the array.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to
compression.
read_only : bool, optional
True if array should be protected against modification.
synchronizer : object, optional
Array synchronizer.
Notes
-----
WARNING: This is an experimental feature and should be used with care.
There are plenty of ways to generate errors and/or cause data
corruption.
Examples
--------
Bypass filters:
>>> import zarr
>>> import numpy as np
>>> np.random.seed(42)
>>> labels = ['female', 'male']
>>> data = np.random.choice(labels, size=10000)
>>> filters = [zarr.Categorize(labels=labels,
... dtype=data.dtype,
... astype='u1')]
>>> a = zarr.array(data, chunks=1000, filters=filters)
>>> a[:]
array(['female', 'male', 'female', ..., 'male', 'male', 'female'],
dtype='<U6')
>>> v = a.view(dtype='u1', filters=[])
>>> v.is_view
True
>>> v[:]
array([1, 2, 1, ..., 2, 2, 1], dtype=uint8)
Views can be used to modify data:
>>> x = v[:]
>>> x.sort()
>>> v[:] = x
>>> v[:]
array([1, 1, 1, ..., 2, 2, 2], dtype=uint8)
>>> a[:]
array(['female', 'female', 'female', ..., 'male', 'male', 'male'],
dtype='<U6')
View as a different dtype with the same item size:
>>> data = np.random.randint(0, 2, size=10000, dtype='u1')
>>> a = zarr.array(data, chunks=1000)
>>> a[:]
array([0, 0, 1, ..., 1, 0, 0], dtype=uint8)
>>> v = a.view(dtype=bool)
>>> v[:]
array([False, False, True, ..., True, False, False])
>>> np.all(a[:].view(dtype=bool) == v[:])
True
An array can be viewed with a dtype with a different item size, however
some care is needed to adjust the shape and chunk shape so that chunk
data is interpreted correctly:
>>> data = np.arange(10000, dtype='u2')
>>> a = zarr.array(data, chunks=1000)
>>> a[:10]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)
>>> v = a.view(dtype='u1', shape=20000, chunks=2000)
>>> v[:10]
array([0, 0, 1, 0, 2, 0, 3, 0, 4, 0], dtype=uint8)
>>> np.all(a[:].view('u1') == v[:])
True
Change fill value for uninitialized chunks:
>>> a = zarr.full(10000, chunks=1000, fill_value=-1, dtype='i1')
>>> a[:]
array([-1, -1, -1, ..., -1, -1, -1], dtype=int8)
>>> v = a.view(fill_value=42)
>>> v[:]
array([42, 42, 42, ..., 42, 42, 42], dtype=int8)
Note that resizing or appending to views is not permitted:
>>> a = zarr.empty(10000)
>>> v = a.view()
>>> try:
... v.resize(20000)
... except PermissionError as e:
... print(e)
operation not permitted for views
"""; 43, assignment; 44, assignment; 45, assignment; 46, comparison_operator:read_only is None; 47, block; 48, comparison_operator:synchronizer is None; 49, block; 50, assignment; 51, assignment; 52, comparison_operator:dtype is None; 53, block; 54, else_clause; 55, comparison_operator:shape is None; 56, block; 57, else_clause; 58, comparison_operator:chunks is not None; 59, block; 60, comparison_operator:fill_value is not None; 61, block; 62, comparison_operator:filters is not None; 63, block; 64, identifier:a; 65, identifier:store; 66, attribute; 67, identifier:chunk_store; 68, attribute; 69, identifier:path; 70, attribute; 71, identifier:read_only; 72, None; 73, expression_statement; 74, identifier:synchronizer; 75, None; 76, expression_statement; 77, identifier:a; 78, call; 79, attribute; 80, True; 81, identifier:dtype; 82, None; 83, expression_statement; 84, block; 85, identifier:shape; 86, None; 87, expression_statement; 88, block; 89, identifier:chunks; 90, None; 91, expression_statement; 92, expression_statement; 93, identifier:fill_value; 94, None; 95, expression_statement; 96, identifier:filters; 97, None; 98, expression_statement; 99, identifier:self; 100, identifier:_store; 101, identifier:self; 102, identifier:_chunk_store; 103, identifier:self; 104, identifier:_path; 105, assignment; 106, assignment; 107, identifier:Array; 108, argument_list; 109, identifier:a; 110, identifier:_is_view; 111, assignment; 112, expression_statement; 113, expression_statement; 114, assignment; 115, expression_statement; 116, expression_statement; 117, assignment; 118, assignment; 119, assignment; 120, assignment; 121, identifier:read_only; 122, attribute; 123, identifier:synchronizer; 124, attribute; 125, keyword_argument; 126, keyword_argument; 127, keyword_argument; 128, keyword_argument; 129, keyword_argument; 130, keyword_argument; 131, identifier:dtype; 132, attribute; 133, assignment; 134, assignment; 135, identifier:shape; 136, attribute; 137, assignment; 138, assignment; 139, identifier:chunks; 140, call; 141, attribute; 142, identifier:chunks; 143, attribute; 144, identifier:fill_value; 145, attribute; 146, identifier:filters; 147, identifier:self; 148, identifier:_read_only; 149, identifier:self; 150, identifier:_synchronizer; 151, identifier:store; 152, identifier:store; 153, identifier:path; 154, identifier:path; 155, identifier:chunk_store; 156, identifier:chunk_store; 157, identifier:read_only; 158, identifier:read_only; 159, identifier:synchronizer; 160, identifier:synchronizer; 161, identifier:cache_metadata; 162, True; 163, identifier:self; 164, identifier:_dtype; 165, identifier:dtype; 166, call; 167, attribute; 168, identifier:dtype; 169, identifier:self; 170, identifier:_shape; 171, identifier:shape; 172, call; 173, attribute; 174, identifier:shape; 175, identifier:normalize_chunks; 176, argument_list; 177, identifier:a; 178, identifier:_chunks; 179, identifier:a; 180, identifier:_fill_value; 181, identifier:a; 182, identifier:_filters; 183, attribute; 184, argument_list; 185, identifier:a; 186, identifier:_dtype; 187, identifier:normalize_shape; 188, argument_list; 189, identifier:a; 190, identifier:_shape; 191, identifier:chunks; 192, identifier:shape; 193, attribute; 194, identifier:np; 195, identifier:dtype; 196, identifier:dtype; 197, identifier:shape; 198, identifier:dtype; 199, identifier:itemsize | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 6, 28; 6, 29; 7, 30; 7, 31; 8, 32; 8, 33; 9, 34; 9, 35; 10, 36; 10, 37; 11, 38; 11, 39; 12, 40; 12, 41; 13, 42; 14, 43; 15, 44; 16, 45; 17, 46; 17, 47; 18, 48; 18, 49; 19, 50; 20, 51; 22, 52; 22, 53; 22, 54; 23, 55; 23, 56; 23, 57; 24, 58; 24, 59; 25, 60; 25, 61; 26, 62; 26, 63; 27, 64; 43, 65; 43, 66; 44, 67; 44, 68; 45, 69; 45, 70; 46, 71; 46, 72; 47, 73; 48, 74; 48, 75; 49, 76; 50, 77; 50, 78; 51, 79; 51, 80; 52, 81; 52, 82; 53, 83; 54, 84; 55, 85; 55, 86; 56, 87; 57, 88; 58, 89; 58, 90; 59, 91; 59, 92; 60, 93; 60, 94; 61, 95; 62, 96; 62, 97; 63, 98; 66, 99; 66, 100; 68, 101; 68, 102; 70, 103; 70, 104; 73, 105; 76, 106; 78, 107; 78, 108; 79, 109; 79, 110; 83, 111; 84, 112; 84, 113; 87, 114; 88, 115; 88, 116; 91, 117; 92, 118; 95, 119; 98, 120; 105, 121; 105, 122; 106, 123; 106, 124; 108, 125; 108, 126; 108, 127; 108, 128; 108, 129; 108, 130; 111, 131; 111, 132; 112, 133; 113, 134; 114, 135; 114, 136; 115, 137; 116, 138; 117, 139; 117, 140; 118, 141; 118, 142; 119, 143; 119, 144; 120, 145; 120, 146; 122, 147; 122, 148; 124, 149; 124, 150; 125, 151; 125, 152; 126, 153; 126, 154; 127, 155; 127, 156; 128, 157; 128, 158; 129, 159; 129, 160; 130, 161; 130, 162; 132, 163; 132, 164; 133, 165; 133, 166; 134, 167; 134, 168; 136, 169; 136, 170; 137, 171; 137, 172; 138, 173; 138, 174; 140, 175; 140, 176; 141, 177; 141, 178; 143, 179; 143, 180; 145, 181; 145, 182; 166, 183; 166, 184; 167, 185; 167, 186; 172, 187; 172, 188; 173, 189; 173, 190; 176, 191; 176, 192; 176, 193; 183, 194; 183, 195; 184, 196; 188, 197; 193, 198; 193, 199 | def view(self, shape=None, chunks=None, dtype=None,
fill_value=None, filters=None, read_only=None,
synchronizer=None):
"""Return an array sharing the same data.
Parameters
----------
shape : int or tuple of ints
Array shape.
chunks : int or tuple of ints, optional
Chunk shape.
dtype : string or dtype, optional
NumPy dtype.
fill_value : object
Default value to use for uninitialized portions of the array.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to
compression.
read_only : bool, optional
True if array should be protected against modification.
synchronizer : object, optional
Array synchronizer.
Notes
-----
WARNING: This is an experimental feature and should be used with care.
There are plenty of ways to generate errors and/or cause data
corruption.
Examples
--------
Bypass filters:
>>> import zarr
>>> import numpy as np
>>> np.random.seed(42)
>>> labels = ['female', 'male']
>>> data = np.random.choice(labels, size=10000)
>>> filters = [zarr.Categorize(labels=labels,
... dtype=data.dtype,
... astype='u1')]
>>> a = zarr.array(data, chunks=1000, filters=filters)
>>> a[:]
array(['female', 'male', 'female', ..., 'male', 'male', 'female'],
dtype='<U6')
>>> v = a.view(dtype='u1', filters=[])
>>> v.is_view
True
>>> v[:]
array([1, 2, 1, ..., 2, 2, 1], dtype=uint8)
Views can be used to modify data:
>>> x = v[:]
>>> x.sort()
>>> v[:] = x
>>> v[:]
array([1, 1, 1, ..., 2, 2, 2], dtype=uint8)
>>> a[:]
array(['female', 'female', 'female', ..., 'male', 'male', 'male'],
dtype='<U6')
View as a different dtype with the same item size:
>>> data = np.random.randint(0, 2, size=10000, dtype='u1')
>>> a = zarr.array(data, chunks=1000)
>>> a[:]
array([0, 0, 1, ..., 1, 0, 0], dtype=uint8)
>>> v = a.view(dtype=bool)
>>> v[:]
array([False, False, True, ..., True, False, False])
>>> np.all(a[:].view(dtype=bool) == v[:])
True
An array can be viewed with a dtype with a different item size, however
some care is needed to adjust the shape and chunk shape so that chunk
data is interpreted correctly:
>>> data = np.arange(10000, dtype='u2')
>>> a = zarr.array(data, chunks=1000)
>>> a[:10]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)
>>> v = a.view(dtype='u1', shape=20000, chunks=2000)
>>> v[:10]
array([0, 0, 1, 0, 2, 0, 3, 0, 4, 0], dtype=uint8)
>>> np.all(a[:].view('u1') == v[:])
True
Change fill value for uninitialized chunks:
>>> a = zarr.full(10000, chunks=1000, fill_value=-1, dtype='i1')
>>> a[:]
array([-1, -1, -1, ..., -1, -1, -1], dtype=int8)
>>> v = a.view(fill_value=42)
>>> v[:]
array([42, 42, 42, ..., 42, 42, 42], dtype=int8)
Note that resizing or appending to views is not permitted:
>>> a = zarr.empty(10000)
>>> v = a.view()
>>> try:
... v.resize(20000)
... except PermissionError as e:
... print(e)
operation not permitted for views
"""
store = self._store
chunk_store = self._chunk_store
path = self._path
if read_only is None:
read_only = self._read_only
if synchronizer is None:
synchronizer = self._synchronizer
a = Array(store=store, path=path, chunk_store=chunk_store, read_only=read_only,
synchronizer=synchronizer, cache_metadata=True)
a._is_view = True
# allow override of some properties
if dtype is None:
dtype = self._dtype
else:
dtype = np.dtype(dtype)
a._dtype = dtype
if shape is None:
shape = self._shape
else:
shape = normalize_shape(shape)
a._shape = shape
if chunks is not None:
chunks = normalize_chunks(chunks, shape, dtype.itemsize)
a._chunks = chunks
if fill_value is not None:
a._fill_value = fill_value
if filters is not None:
a._filters = filters
return a |
0, module; 1, function_definition; 2, function_name:image_field_data; 3, parameters; 4, block; 5, identifier:request; 6, default_parameter; 7, expression_statement; 8, try_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, if_statement; 13, return_statement; 14, identifier:include_empty_option; 15, False; 16, comment:"""Returns a list of tuples of all images.
Generates a sorted list of images available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples
"""; 17, block; 18, except_clause; 19, call; 20, assignment; 21, identifier:image; 22, identifier:images; 23, block; 24, not_operator; 25, block; 26, identifier:images_list; 27, expression_statement; 28, identifier:Exception; 29, block; 30, attribute; 31, argument_list; 32, identifier:images_list; 33, list; 34, expression_statement; 35, expression_statement; 36, identifier:images; 37, return_statement; 38, assignment; 39, expression_statement; 40, identifier:images; 41, identifier:sort; 42, keyword_argument; 43, tuple; 44, assignment; 45, call; 46, list; 47, identifier:images; 48, call; 49, call; 50, identifier:key; 51, lambda; 52, string; 53, call; 54, identifier:image_label; 55, call; 56, attribute; 57, argument_list; 58, tuple; 59, identifier:get_available_images; 60, argument_list; 61, attribute; 62, argument_list; 63, lambda_parameters; 64, attribute; 65, identifier:_; 66, argument_list; 67, attribute; 68, argument_list; 69, identifier:images_list; 70, identifier:append; 71, tuple; 72, string:""; 73, call; 74, identifier:request; 75, attribute; 76, identifier:exceptions; 77, identifier:handle; 78, identifier:request; 79, call; 80, identifier:c; 81, identifier:c; 82, identifier:name; 83, string; 84, string:u"{} ({})"; 85, identifier:format; 86, attribute; 87, call; 88, attribute; 89, identifier:image_label; 90, identifier:_; 91, argument_list; 92, attribute; 93, identifier:project_id; 94, identifier:_; 95, argument_list; 96, string_content:Select Image; 97, identifier:image; 98, identifier:name; 99, identifier:filesizeformat; 100, argument_list; 101, identifier:image; 102, identifier:id; 103, string:"No images available"; 104, identifier:request; 105, identifier:user; 106, string; 107, attribute; 108, string_content:Unable to retrieve images; 109, identifier:image; 110, identifier:size | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 6, 15; 7, 16; 8, 17; 8, 18; 9, 19; 10, 20; 11, 21; 11, 22; 11, 23; 12, 24; 12, 25; 13, 26; 17, 27; 18, 28; 18, 29; 19, 30; 19, 31; 20, 32; 20, 33; 23, 34; 23, 35; 24, 36; 25, 37; 27, 38; 29, 39; 30, 40; 30, 41; 31, 42; 33, 43; 34, 44; 35, 45; 37, 46; 38, 47; 38, 48; 39, 49; 42, 50; 42, 51; 43, 52; 43, 53; 44, 54; 44, 55; 45, 56; 45, 57; 46, 58; 48, 59; 48, 60; 49, 61; 49, 62; 51, 63; 51, 64; 53, 65; 53, 66; 55, 67; 55, 68; 56, 69; 56, 70; 57, 71; 58, 72; 58, 73; 60, 74; 60, 75; 61, 76; 61, 77; 62, 78; 62, 79; 63, 80; 64, 81; 64, 82; 66, 83; 67, 84; 67, 85; 68, 86; 68, 87; 71, 88; 71, 89; 73, 90; 73, 91; 75, 92; 75, 93; 79, 94; 79, 95; 83, 96; 86, 97; 86, 98; 87, 99; 87, 100; 88, 101; 88, 102; 91, 103; 92, 104; 92, 105; 95, 106; 100, 107; 106, 108; 107, 109; 107, 110 | def image_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all images.
Generates a sorted list of images available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples
"""
try:
images = get_available_images(request, request.user.project_id)
except Exception:
exceptions.handle(request, _('Unable to retrieve images'))
images.sort(key=lambda c: c.name)
images_list = [('', _('Select Image'))]
for image in images:
image_label = u"{} ({})".format(image.name, filesizeformat(image.size))
images_list.append((image.id, image_label))
if not images:
return [("", _("No images available")), ]
return images_list |
0, module; 1, function_definition; 2, function_name:sort_flavor_list; 3, parameters; 4, block; 5, identifier:request; 6, identifier:flavors; 7, default_parameter; 8, expression_statement; 9, function_definition; 10, try_statement; 11, identifier:with_menu_label; 12, True; 13, comment:"""Utility method to sort a list of flavors.
By default, returns the available flavors, sorted by RAM usage (ascending).
Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict
in ``local_settings.py``.
"""; 14, function_name:get_key; 15, parameters; 16, block; 17, block; 18, except_clause; 19, identifier:flavor; 20, identifier:sort_key; 21, try_statement; 22, expression_statement; 23, expression_statement; 24, expression_statement; 25, if_statement; 26, if_statement; 27, return_statement; 28, identifier:Exception; 29, block; 30, block; 31, except_clause; 32, assignment; 33, assignment; 34, assignment; 35, not_operator; 36, block; 37, else_clause; 38, identifier:with_menu_label; 39, block; 40, else_clause; 41, identifier:flavor_list; 42, expression_statement; 43, return_statement; 44, return_statement; 45, identifier:AttributeError; 46, block; 47, identifier:flavor_sort; 48, call; 49, identifier:sort_key; 50, call; 51, identifier:rev; 52, call; 53, call; 54, function_definition; 55, block; 56, expression_statement; 57, block; 58, call; 59, list; 60, call; 61, expression_statement; 62, return_statement; 63, identifier:getattr; 64, argument_list; 65, attribute; 66, argument_list; 67, attribute; 68, argument_list; 69, identifier:callable; 70, argument_list; 71, function_name:key; 72, parameters; 73, block; 74, expression_statement; 75, assignment; 76, expression_statement; 77, attribute; 78, argument_list; 79, identifier:getattr; 80, argument_list; 81, call; 82, call; 83, identifier:settings; 84, string; 85, dictionary; 86, identifier:flavor_sort; 87, identifier:get; 88, string; 89, string; 90, identifier:flavor_sort; 91, identifier:get; 92, string; 93, False; 94, identifier:sort_key; 95, identifier:flavor; 96, return_statement; 97, assignment; 98, identifier:flavor_list; 99, list_comprehension; 100, assignment; 101, identifier:exceptions; 102, identifier:handle; 103, identifier:request; 104, call; 105, identifier:flavor; 106, identifier:sort_key; 107, attribute; 108, argument_list; 109, identifier:getattr; 110, argument_list; 111, string_content:CREATE_INSTANCE_FLAVOR_SORT; 112, string_content:key; 113, string_content:ram; 114, string_content:reverse; 115, call; 116, identifier:key; 117, identifier:sort_key; 118, tuple; 119, for_in_clause; 120, identifier:flavor_list; 121, call; 122, identifier:_; 123, argument_list; 124, identifier:LOG; 125, identifier:warning; 126, concatenated_string; 127, identifier:sort_key; 128, identifier:flavor; 129, string; 130, identifier:get_key; 131, argument_list; 132, attribute; 133, binary_operator:'%s' % flavor.name; 134, identifier:flavor; 135, call; 136, identifier:sorted; 137, argument_list; 138, string; 139, string:'Could not find sort key "%s". Using the default '; 140, string:'"ram" instead.'; 141, string_content:ram; 142, identifier:flavor; 143, identifier:sort_key; 144, identifier:flavor; 145, identifier:id; 146, string; 147, attribute; 148, identifier:sorted; 149, argument_list; 150, identifier:flavors; 151, keyword_argument; 152, keyword_argument; 153, string_content:Unable to sort instance flavors.; 154, string_content:%s; 155, identifier:flavor; 156, identifier:name; 157, identifier:flavors; 158, keyword_argument; 159, keyword_argument; 160, identifier:key; 161, identifier:key; 162, identifier:reverse; 163, identifier:rev; 164, identifier:key; 165, identifier:key; 166, identifier:reverse; 167, identifier:rev | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 7, 11; 7, 12; 8, 13; 9, 14; 9, 15; 9, 16; 10, 17; 10, 18; 15, 19; 15, 20; 16, 21; 17, 22; 17, 23; 17, 24; 17, 25; 17, 26; 17, 27; 18, 28; 18, 29; 21, 30; 21, 31; 22, 32; 23, 33; 24, 34; 25, 35; 25, 36; 25, 37; 26, 38; 26, 39; 26, 40; 27, 41; 29, 42; 29, 43; 30, 44; 31, 45; 31, 46; 32, 47; 32, 48; 33, 49; 33, 50; 34, 51; 34, 52; 35, 53; 36, 54; 37, 55; 39, 56; 40, 57; 42, 58; 43, 59; 44, 60; 46, 61; 46, 62; 48, 63; 48, 64; 50, 65; 50, 66; 52, 67; 52, 68; 53, 69; 53, 70; 54, 71; 54, 72; 54, 73; 55, 74; 56, 75; 57, 76; 58, 77; 58, 78; 60, 79; 60, 80; 61, 81; 62, 82; 64, 83; 64, 84; 64, 85; 65, 86; 65, 87; 66, 88; 66, 89; 67, 90; 67, 91; 68, 92; 68, 93; 70, 94; 72, 95; 73, 96; 74, 97; 75, 98; 75, 99; 76, 100; 77, 101; 77, 102; 78, 103; 78, 104; 80, 105; 80, 106; 81, 107; 81, 108; 82, 109; 82, 110; 84, 111; 88, 112; 89, 113; 92, 114; 96, 115; 97, 116; 97, 117; 99, 118; 99, 119; 100, 120; 100, 121; 104, 122; 104, 123; 107, 124; 107, 125; 108, 126; 108, 127; 110, 128; 110, 129; 115, 130; 115, 131; 118, 132; 118, 133; 119, 134; 119, 135; 121, 136; 121, 137; 123, 138; 126, 139; 126, 140; 129, 141; 131, 142; 131, 143; 132, 144; 132, 145; 133, 146; 133, 147; 135, 148; 135, 149; 137, 150; 137, 151; 137, 152; 138, 153; 146, 154; 147, 155; 147, 156; 149, 157; 149, 158; 149, 159; 151, 160; 151, 161; 152, 162; 152, 163; 158, 164; 158, 165; 159, 166; 159, 167 | def sort_flavor_list(request, flavors, with_menu_label=True):
"""Utility method to sort a list of flavors.
By default, returns the available flavors, sorted by RAM usage (ascending).
Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict
in ``local_settings.py``.
"""
def get_key(flavor, sort_key):
try:
return getattr(flavor, sort_key)
except AttributeError:
LOG.warning('Could not find sort key "%s". Using the default '
'"ram" instead.', sort_key)
return getattr(flavor, 'ram')
try:
flavor_sort = getattr(settings, 'CREATE_INSTANCE_FLAVOR_SORT', {})
sort_key = flavor_sort.get('key', 'ram')
rev = flavor_sort.get('reverse', False)
if not callable(sort_key):
def key(flavor):
return get_key(flavor, sort_key)
else:
key = sort_key
if with_menu_label:
flavor_list = [(flavor.id, '%s' % flavor.name)
for flavor in sorted(flavors, key=key, reverse=rev)]
else:
flavor_list = sorted(flavors, key=key, reverse=rev)
return flavor_list
except Exception:
exceptions.handle(request,
_('Unable to sort instance flavors.'))
return [] |
0, module; 1, function_definition; 2, function_name:image_list_detailed; 3, parameters; 4, block; 5, identifier:request; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, dictionary_splat_pattern; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, if_statement; 17, expression_statement; 18, expression_statement; 19, if_statement; 20, expression_statement; 21, if_statement; 22, expression_statement; 23, expression_statement; 24, expression_statement; 25, if_statement; 26, comment:# TODO(jpichon): Do it better; 27, expression_statement; 28, for_statement; 29, return_statement; 30, identifier:marker; 31, None; 32, identifier:sort_dir; 33, string; 34, identifier:sort_key; 35, string; 36, identifier:filters; 37, None; 38, identifier:paginate; 39, False; 40, identifier:reversed_order; 41, False; 42, identifier:kwargs; 43, comment:"""Thin layer above glanceclient, for handling pagination issues.
It provides iterating both forward and backward on top of ascetic
OpenStack pagination API - which natively supports only iterating forward
through the entries. Thus in order to retrieve list of objects at previous
page, a request with the reverse entries order had to be made to Glance,
using the first object id on current page as the marker - restoring
the original items ordering before sending them back to the UI.
:param request:
The request object coming from browser to be passed further into
Glance service.
:param marker:
The id of an object which defines a starting point of a query sent to
Glance service.
:param sort_dir:
The direction by which the resulting image list throughout all pages
(if pagination is enabled) will be sorted. Could be either 'asc'
(ascending) or 'desc' (descending), defaults to 'desc'.
:param sort_key:
The name of key by by which the resulting image list throughout all
pages (if pagination is enabled) will be sorted. Defaults to
'created_at'.
:param filters:
A dictionary of filters passed as is to Glance service.
:param paginate:
Whether the pagination is enabled. If it is, then the number of
entries on a single page of images table is limited to the specific
number stored in browser cookies.
:param reversed_order:
Set this flag to True when it's necessary to get a reversed list of
images from Glance (used for navigating the images list back in UI).
"""; 44, assignment; 45, assignment; 46, identifier:paginate; 47, block; 48, else_clause; 49, call; 50, assignment; 51, identifier:marker; 52, block; 53, assignment; 54, not_operator; 55, block; 56, else_clause; 57, assignment; 58, assignment; 59, assignment; 60, identifier:paginate; 61, block; 62, else_clause; 63, assignment; 64, identifier:image; 65, identifier:images; 66, block; 67, expression_list; 68, string_content:desc; 69, string_content:created_at; 70, identifier:limit; 71, call; 72, identifier:page_size; 73, call; 74, expression_statement; 75, block; 76, identifier:_normalize_list_input; 77, argument_list; 78, identifier:kwargs; 79, dictionary; 80, expression_statement; 81, subscript; 82, identifier:sort_key; 83, identifier:reversed_order; 84, expression_statement; 85, block; 86, identifier:images_iter; 87, call; 88, identifier:has_prev_data; 89, False; 90, identifier:has_more_data; 91, False; 92, expression_statement; 93, comment:# first and middle page condition; 94, if_statement; 95, comment:# restore the original ordering here; 96, if_statement; 97, block; 98, identifier:wrapped_images; 99, list; 100, expression_statement; 101, identifier:wrapped_images; 102, identifier:has_more_data; 103, identifier:has_prev_data; 104, identifier:getattr; 105, argument_list; 106, attribute; 107, argument_list; 108, assignment; 109, expression_statement; 110, identifier:filters; 111, dictionary_splat; 112, pair; 113, assignment; 114, identifier:kwargs; 115, string; 116, assignment; 117, expression_statement; 118, attribute; 119, argument_list; 120, assignment; 121, comparison_operator:len(images) > page_size; 122, block; 123, comment:# first page condition when reached via prev back; 124, elif_clause; 125, comment:# last page condition; 126, elif_clause; 127, identifier:reversed_order; 128, block; 129, expression_statement; 130, call; 131, identifier:settings; 132, string; 133, integer:1000; 134, identifier:utils; 135, identifier:get_page_size; 136, identifier:request; 137, identifier:request_size; 138, binary_operator:page_size + 1; 139, assignment; 140, identifier:kwargs; 141, string; 142, boolean_operator; 143, subscript; 144, identifier:marker; 145, string_content:sort_key; 146, subscript; 147, identifier:sort_dir; 148, assignment; 149, attribute; 150, identifier:list; 151, keyword_argument; 152, keyword_argument; 153, dictionary_splat; 154, identifier:images; 155, call; 156, call; 157, identifier:page_size; 158, expression_statement; 159, expression_statement; 160, comment:# middle page condition; 161, if_statement; 162, boolean_operator; 163, block; 164, comparison_operator:marker is not None; 165, block; 166, expression_statement; 167, assignment; 168, attribute; 169, argument_list; 170, string_content:API_RESULT_LIMIT; 171, identifier:page_size; 172, integer:1; 173, identifier:request_size; 174, identifier:limit; 175, string_content:filters; 176, identifier:filters; 177, dictionary; 178, identifier:kwargs; 179, string; 180, identifier:kwargs; 181, string; 182, subscript; 183, conditional_expression:'desc' if sort_dir == 'asc' else 'asc'; 184, call; 185, identifier:images; 186, identifier:page_size; 187, identifier:request_size; 188, identifier:limit; 189, identifier:limit; 190, identifier:kwargs; 191, identifier:list; 192, argument_list; 193, identifier:len; 194, argument_list; 195, call; 196, assignment; 197, comparison_operator:marker is not None; 198, block; 199, identifier:reversed_order; 200, comparison_operator:marker is not None; 201, expression_statement; 202, identifier:marker; 203, None; 204, expression_statement; 205, assignment; 206, identifier:images; 207, call; 208, identifier:wrapped_images; 209, identifier:append; 210, call; 211, string_content:marker; 212, string_content:sort_dir; 213, identifier:kwargs; 214, string; 215, string; 216, comparison_operator:sort_dir == 'asc'; 217, string; 218, identifier:glanceclient; 219, argument_list; 220, call; 221, identifier:images; 222, attribute; 223, argument_list; 224, identifier:has_more_data; 225, True; 226, identifier:marker; 227, None; 228, expression_statement; 229, identifier:marker; 230, None; 231, assignment; 232, assignment; 233, identifier:images; 234, call; 235, identifier:list; 236, argument_list; 237, identifier:Image; 238, argument_list; 239, string_content:sort_dir; 240, string_content:desc; 241, identifier:sort_dir; 242, string; 243, string_content:asc; 244, identifier:request; 245, attribute; 246, argument_list; 247, identifier:images; 248, identifier:pop; 249, unary_operator; 250, assignment; 251, identifier:has_more_data; 252, True; 253, identifier:has_prev_data; 254, True; 255, identifier:sorted; 256, argument_list; 257, identifier:images_iter; 258, identifier:image; 259, string_content:asc; 260, identifier:itertools; 261, identifier:islice; 262, identifier:images_iter; 263, identifier:request_size; 264, integer:1; 265, identifier:has_prev_data; 266, True; 267, identifier:images; 268, keyword_argument; 269, keyword_argument; 270, identifier:key; 271, lambda; 272, identifier:reverse; 273, parenthesized_expression; 274, lambda_parameters; 275, call; 276, comparison_operator:sort_dir == 'desc'; 277, identifier:image; 278, attribute; 279, argument_list; 280, identifier:sort_dir; 281, string; 282, parenthesized_expression; 283, identifier:lower; 284, string_content:desc; 285, boolean_operator; 286, call; 287, string; 288, identifier:getattr; 289, argument_list; 290, identifier:image; 291, identifier:sort_key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 6, 30; 6, 31; 7, 32; 7, 33; 8, 34; 8, 35; 9, 36; 9, 37; 10, 38; 10, 39; 11, 40; 11, 41; 12, 42; 13, 43; 14, 44; 15, 45; 16, 46; 16, 47; 16, 48; 17, 49; 18, 50; 19, 51; 19, 52; 20, 53; 21, 54; 21, 55; 21, 56; 22, 57; 23, 58; 24, 59; 25, 60; 25, 61; 25, 62; 27, 63; 28, 64; 28, 65; 28, 66; 29, 67; 33, 68; 35, 69; 44, 70; 44, 71; 45, 72; 45, 73; 47, 74; 48, 75; 49, 76; 49, 77; 50, 78; 50, 79; 52, 80; 53, 81; 53, 82; 54, 83; 55, 84; 56, 85; 57, 86; 57, 87; 58, 88; 58, 89; 59, 90; 59, 91; 61, 92; 61, 93; 61, 94; 61, 95; 61, 96; 62, 97; 63, 98; 63, 99; 66, 100; 67, 101; 67, 102; 67, 103; 71, 104; 71, 105; 73, 106; 73, 107; 74, 108; 75, 109; 77, 110; 77, 111; 79, 112; 80, 113; 81, 114; 81, 115; 84, 116; 85, 117; 87, 118; 87, 119; 92, 120; 94, 121; 94, 122; 94, 123; 94, 124; 94, 125; 94, 126; 96, 127; 96, 128; 97, 129; 100, 130; 105, 131; 105, 132; 105, 133; 106, 134; 106, 135; 107, 136; 108, 137; 108, 138; 109, 139; 111, 140; 112, 141; 112, 142; 113, 143; 113, 144; 115, 145; 116, 146; 116, 147; 117, 148; 118, 149; 118, 150; 119, 151; 119, 152; 119, 153; 120, 154; 120, 155; 121, 156; 121, 157; 122, 158; 122, 159; 122, 160; 122, 161; 124, 162; 124, 163; 126, 164; 126, 165; 128, 166; 129, 167; 130, 168; 130, 169; 132, 170; 138, 171; 138, 172; 139, 173; 139, 174; 141, 175; 142, 176; 142, 177; 143, 178; 143, 179; 146, 180; 146, 181; 148, 182; 148, 183; 149, 184; 149, 185; 151, 186; 151, 187; 152, 188; 152, 189; 153, 190; 155, 191; 155, 192; 156, 193; 156, 194; 158, 195; 159, 196; 161, 197; 161, 198; 162, 199; 162, 200; 163, 201; 164, 202; 164, 203; 165, 204; 166, 205; 167, 206; 167, 207; 168, 208; 168, 209; 169, 210; 179, 211; 181, 212; 182, 213; 182, 214; 183, 215; 183, 216; 183, 217; 184, 218; 184, 219; 192, 220; 194, 221; 195, 222; 195, 223; 196, 224; 196, 225; 197, 226; 197, 227; 198, 228; 200, 229; 200, 230; 201, 231; 204, 232; 205, 233; 205, 234; 207, 235; 207, 236; 210, 237; 210, 238; 214, 239; 215, 240; 216, 241; 216, 242; 217, 243; 219, 244; 220, 245; 220, 246; 222, 247; 222, 248; 223, 249; 228, 250; 231, 251; 231, 252; 232, 253; 232, 254; 234, 255; 234, 256; 236, 257; 238, 258; 242, 259; 245, 260; 245, 261; 246, 262; 246, 263; 249, 264; 250, 265; 250, 266; 256, 267; 256, 268; 256, 269; 268, 270; 268, 271; 269, 272; 269, 273; 271, 274; 271, 275; 273, 276; 274, 277; 275, 278; 275, 279; 276, 280; 276, 281; 278, 282; 278, 283; 281, 284; 282, 285; 285, 286; 285, 287; 286, 288; 286, 289; 289, 290; 289, 291 | def image_list_detailed(request, marker=None, sort_dir='desc',
sort_key='created_at', filters=None, paginate=False,
reversed_order=False, **kwargs):
"""Thin layer above glanceclient, for handling pagination issues.
It provides iterating both forward and backward on top of ascetic
OpenStack pagination API - which natively supports only iterating forward
through the entries. Thus in order to retrieve list of objects at previous
page, a request with the reverse entries order had to be made to Glance,
using the first object id on current page as the marker - restoring
the original items ordering before sending them back to the UI.
:param request:
The request object coming from browser to be passed further into
Glance service.
:param marker:
The id of an object which defines a starting point of a query sent to
Glance service.
:param sort_dir:
The direction by which the resulting image list throughout all pages
(if pagination is enabled) will be sorted. Could be either 'asc'
(ascending) or 'desc' (descending), defaults to 'desc'.
:param sort_key:
The name of key by by which the resulting image list throughout all
pages (if pagination is enabled) will be sorted. Defaults to
'created_at'.
:param filters:
A dictionary of filters passed as is to Glance service.
:param paginate:
Whether the pagination is enabled. If it is, then the number of
entries on a single page of images table is limited to the specific
number stored in browser cookies.
:param reversed_order:
Set this flag to True when it's necessary to get a reversed list of
images from Glance (used for navigating the images list back in UI).
"""
limit = getattr(settings, 'API_RESULT_LIMIT', 1000)
page_size = utils.get_page_size(request)
if paginate:
request_size = page_size + 1
else:
request_size = limit
_normalize_list_input(filters, **kwargs)
kwargs = {'filters': filters or {}}
if marker:
kwargs['marker'] = marker
kwargs['sort_key'] = sort_key
if not reversed_order:
kwargs['sort_dir'] = sort_dir
else:
kwargs['sort_dir'] = 'desc' if sort_dir == 'asc' else 'asc'
images_iter = glanceclient(request).images.list(page_size=request_size,
limit=limit,
**kwargs)
has_prev_data = False
has_more_data = False
if paginate:
images = list(itertools.islice(images_iter, request_size))
# first and middle page condition
if len(images) > page_size:
images.pop(-1)
has_more_data = True
# middle page condition
if marker is not None:
has_prev_data = True
# first page condition when reached via prev back
elif reversed_order and marker is not None:
has_more_data = True
# last page condition
elif marker is not None:
has_prev_data = True
# restore the original ordering here
if reversed_order:
images = sorted(images, key=lambda image:
(getattr(image, sort_key) or '').lower(),
reverse=(sort_dir == 'desc'))
else:
images = list(images_iter)
# TODO(jpichon): Do it better
wrapped_images = []
for image in images:
wrapped_images.append(Image(image))
return wrapped_images, has_more_data, has_prev_data |
0, module; 1, function_definition; 2, function_name:metadefs_namespace_list; 3, parameters; 4, block; 5, identifier:request; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, comment:# Listing namespaces requires the v2 API. If not supported we return an; 13, comment:# empty array so callers don't need to worry about version checking.; 14, if_statement; 15, if_statement; 16, expression_statement; 17, expression_statement; 18, if_statement; 19, expression_statement; 20, if_statement; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, comment:# Filter the namespaces based on the provided properties_target since this; 25, comment:# is not supported by the metadata namespaces API.; 26, expression_statement; 27, expression_statement; 28, if_statement; 29, expression_statement; 30, expression_statement; 31, if_statement; 32, expression_statement; 33, return_statement; 34, identifier:filters; 35, None; 36, identifier:sort_dir; 37, string; 38, identifier:sort_key; 39, string; 40, identifier:marker; 41, None; 42, identifier:paginate; 43, False; 44, comment:"""Retrieve a listing of Namespaces
:param paginate: If true will perform pagination based on settings.
:param marker: Specifies the namespace of the last-seen namespace.
The typical pattern of limit and marker is to make an
initial limited request and then to use the last
namespace from the response as the marker parameter
in a subsequent limited request. With paginate, limit
is automatically set.
:param sort_dir: The sort direction ('asc' or 'desc').
:param sort_key: The field to sort on (for example, 'created_at'). Default
is namespace. The way base namespaces are loaded into glance
typically at first deployment is done in a single transaction
giving them a potentially unpredictable sort result when using
create_at.
:param filters: specifies addition fields to filter on such as
resource_types.
:returns A tuple of three values:
1) Current page results
2) A boolean of whether or not there are previous page(s).
3) A boolean of whether or not there are more page(s).
"""; 45, comparison_operator:get_version() < 2; 46, block; 47, comparison_operator:filters is None; 48, block; 49, assignment; 50, assignment; 51, identifier:paginate; 52, block; 53, else_clause; 54, assignment; 55, identifier:marker; 56, block; 57, assignment; 58, assignment; 59, assignment; 60, assignment; 61, assignment; 62, boolean_operator; 63, block; 64, assignment; 65, assignment; 66, identifier:paginate; 67, block; 68, else_clause; 69, assignment; 70, expression_list; 71, string_content:asc; 72, string_content:namespace; 73, call; 74, integer:2; 75, return_statement; 76, identifier:filters; 77, None; 78, expression_statement; 79, identifier:limit; 80, call; 81, identifier:page_size; 82, call; 83, expression_statement; 84, block; 85, identifier:kwargs; 86, dictionary; 87, expression_statement; 88, subscript; 89, identifier:sort_dir; 90, subscript; 91, identifier:sort_key; 92, identifier:namespaces_iter; 93, call; 94, identifier:resource_types; 95, call; 96, identifier:properties_target; 97, call; 98, identifier:resource_types; 99, identifier:properties_target; 100, expression_statement; 101, identifier:has_prev_data; 102, False; 103, identifier:has_more_data; 104, False; 105, expression_statement; 106, comment:# first and middle page condition; 107, if_statement; 108, block; 109, identifier:namespaces; 110, list_comprehension; 111, identifier:namespaces; 112, identifier:has_more_data; 113, identifier:has_prev_data; 114, identifier:get_version; 115, argument_list; 116, expression_list; 117, assignment; 118, identifier:getattr; 119, argument_list; 120, attribute; 121, argument_list; 122, assignment; 123, expression_statement; 124, pair; 125, assignment; 126, identifier:kwargs; 127, string; 128, identifier:kwargs; 129, string; 130, attribute; 131, argument_list; 132, attribute; 133, argument_list; 134, attribute; 135, argument_list; 136, assignment; 137, assignment; 138, comparison_operator:len(namespaces) > page_size; 139, block; 140, comment:# first page condition when reached via prev back; 141, elif_clause; 142, comment:# last page condition; 143, elif_clause; 144, expression_statement; 145, call; 146, for_in_clause; 147, list; 148, False; 149, False; 150, identifier:filters; 151, dictionary; 152, identifier:settings; 153, string; 154, integer:1000; 155, identifier:utils; 156, identifier:get_page_size; 157, identifier:request; 158, identifier:request_size; 159, binary_operator:page_size + 1; 160, assignment; 161, string; 162, identifier:filters; 163, subscript; 164, identifier:marker; 165, string_content:sort_dir; 166, string_content:sort_key; 167, attribute; 168, identifier:list; 169, keyword_argument; 170, keyword_argument; 171, dictionary_splat; 172, identifier:filters; 173, identifier:get; 174, string; 175, identifier:filters; 176, identifier:get; 177, string; 178, identifier:namespaces_iter; 179, call; 180, identifier:namespaces; 181, call; 182, call; 183, identifier:page_size; 184, expression_statement; 185, expression_statement; 186, comment:# middle page condition; 187, if_statement; 188, boolean_operator; 189, block; 190, comparison_operator:marker is not None; 191, block; 192, assignment; 193, identifier:Namespace; 194, argument_list; 195, identifier:namespace; 196, identifier:namespaces; 197, string_content:API_RESULT_LIMIT; 198, identifier:page_size; 199, integer:1; 200, identifier:request_size; 201, identifier:limit; 202, string_content:filters; 203, identifier:kwargs; 204, string; 205, call; 206, identifier:metadefs_namespace; 207, identifier:page_size; 208, identifier:request_size; 209, identifier:limit; 210, identifier:limit; 211, identifier:kwargs; 212, string_content:resource_types; 213, string_content:properties_target; 214, identifier:filter_properties_target; 215, argument_list; 216, identifier:list; 217, argument_list; 218, identifier:len; 219, argument_list; 220, call; 221, assignment; 222, comparison_operator:marker is not None; 223, block; 224, comparison_operator:sort_dir == 'desc'; 225, comparison_operator:marker is not None; 226, expression_statement; 227, identifier:marker; 228, None; 229, expression_statement; 230, identifier:namespaces; 231, call; 232, identifier:namespace; 233, string_content:marker; 234, identifier:glanceclient; 235, argument_list; 236, identifier:namespaces_iter; 237, identifier:resource_types; 238, identifier:properties_target; 239, call; 240, identifier:namespaces; 241, attribute; 242, argument_list; 243, identifier:has_more_data; 244, True; 245, identifier:marker; 246, None; 247, expression_statement; 248, identifier:sort_dir; 249, string; 250, identifier:marker; 251, None; 252, assignment; 253, assignment; 254, identifier:list; 255, argument_list; 256, identifier:request; 257, string; 258, attribute; 259, argument_list; 260, identifier:namespaces; 261, identifier:pop; 262, unary_operator; 263, assignment; 264, string_content:desc; 265, identifier:has_more_data; 266, True; 267, identifier:has_prev_data; 268, True; 269, identifier:namespaces_iter; 270, string_content:2; 271, identifier:itertools; 272, identifier:islice; 273, identifier:namespaces_iter; 274, identifier:request_size; 275, integer:1; 276, identifier:has_prev_data; 277, True | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 4, 30; 4, 31; 4, 32; 4, 33; 6, 34; 6, 35; 7, 36; 7, 37; 8, 38; 8, 39; 9, 40; 9, 41; 10, 42; 10, 43; 11, 44; 14, 45; 14, 46; 15, 47; 15, 48; 16, 49; 17, 50; 18, 51; 18, 52; 18, 53; 19, 54; 20, 55; 20, 56; 21, 57; 22, 58; 23, 59; 26, 60; 27, 61; 28, 62; 28, 63; 29, 64; 30, 65; 31, 66; 31, 67; 31, 68; 32, 69; 33, 70; 37, 71; 39, 72; 45, 73; 45, 74; 46, 75; 47, 76; 47, 77; 48, 78; 49, 79; 49, 80; 50, 81; 50, 82; 52, 83; 53, 84; 54, 85; 54, 86; 56, 87; 57, 88; 57, 89; 58, 90; 58, 91; 59, 92; 59, 93; 60, 94; 60, 95; 61, 96; 61, 97; 62, 98; 62, 99; 63, 100; 64, 101; 64, 102; 65, 103; 65, 104; 67, 105; 67, 106; 67, 107; 68, 108; 69, 109; 69, 110; 70, 111; 70, 112; 70, 113; 73, 114; 73, 115; 75, 116; 78, 117; 80, 118; 80, 119; 82, 120; 82, 121; 83, 122; 84, 123; 86, 124; 87, 125; 88, 126; 88, 127; 90, 128; 90, 129; 93, 130; 93, 131; 95, 132; 95, 133; 97, 134; 97, 135; 100, 136; 105, 137; 107, 138; 107, 139; 107, 140; 107, 141; 107, 142; 107, 143; 108, 144; 110, 145; 110, 146; 116, 147; 116, 148; 116, 149; 117, 150; 117, 151; 119, 152; 119, 153; 119, 154; 120, 155; 120, 156; 121, 157; 122, 158; 122, 159; 123, 160; 124, 161; 124, 162; 125, 163; 125, 164; 127, 165; 129, 166; 130, 167; 130, 168; 131, 169; 131, 170; 131, 171; 132, 172; 132, 173; 133, 174; 134, 175; 134, 176; 135, 177; 136, 178; 136, 179; 137, 180; 137, 181; 138, 182; 138, 183; 139, 184; 139, 185; 139, 186; 139, 187; 141, 188; 141, 189; 143, 190; 143, 191; 144, 192; 145, 193; 145, 194; 146, 195; 146, 196; 153, 197; 159, 198; 159, 199; 160, 200; 160, 201; 161, 202; 163, 203; 163, 204; 167, 205; 167, 206; 169, 207; 169, 208; 170, 209; 170, 210; 171, 211; 174, 212; 177, 213; 179, 214; 179, 215; 181, 216; 181, 217; 182, 218; 182, 219; 184, 220; 185, 221; 187, 222; 187, 223; 188, 224; 188, 225; 189, 226; 190, 227; 190, 228; 191, 229; 192, 230; 192, 231; 194, 232; 204, 233; 205, 234; 205, 235; 215, 236; 215, 237; 215, 238; 217, 239; 219, 240; 220, 241; 220, 242; 221, 243; 221, 244; 222, 245; 222, 246; 223, 247; 224, 248; 224, 249; 225, 250; 225, 251; 226, 252; 229, 253; 231, 254; 231, 255; 235, 256; 235, 257; 239, 258; 239, 259; 241, 260; 241, 261; 242, 262; 247, 263; 249, 264; 252, 265; 252, 266; 253, 267; 253, 268; 255, 269; 257, 270; 258, 271; 258, 272; 259, 273; 259, 274; 262, 275; 263, 276; 263, 277 | def metadefs_namespace_list(request,
filters=None,
sort_dir='asc',
sort_key='namespace',
marker=None,
paginate=False):
"""Retrieve a listing of Namespaces
:param paginate: If true will perform pagination based on settings.
:param marker: Specifies the namespace of the last-seen namespace.
The typical pattern of limit and marker is to make an
initial limited request and then to use the last
namespace from the response as the marker parameter
in a subsequent limited request. With paginate, limit
is automatically set.
:param sort_dir: The sort direction ('asc' or 'desc').
:param sort_key: The field to sort on (for example, 'created_at'). Default
is namespace. The way base namespaces are loaded into glance
typically at first deployment is done in a single transaction
giving them a potentially unpredictable sort result when using
create_at.
:param filters: specifies addition fields to filter on such as
resource_types.
:returns A tuple of three values:
1) Current page results
2) A boolean of whether or not there are previous page(s).
3) A boolean of whether or not there are more page(s).
"""
# Listing namespaces requires the v2 API. If not supported we return an
# empty array so callers don't need to worry about version checking.
if get_version() < 2:
return [], False, False
if filters is None:
filters = {}
limit = getattr(settings, 'API_RESULT_LIMIT', 1000)
page_size = utils.get_page_size(request)
if paginate:
request_size = page_size + 1
else:
request_size = limit
kwargs = {'filters': filters}
if marker:
kwargs['marker'] = marker
kwargs['sort_dir'] = sort_dir
kwargs['sort_key'] = sort_key
namespaces_iter = glanceclient(request, '2').metadefs_namespace.list(
page_size=request_size, limit=limit, **kwargs)
# Filter the namespaces based on the provided properties_target since this
# is not supported by the metadata namespaces API.
resource_types = filters.get('resource_types')
properties_target = filters.get('properties_target')
if resource_types and properties_target:
namespaces_iter = filter_properties_target(namespaces_iter,
resource_types,
properties_target)
has_prev_data = False
has_more_data = False
if paginate:
namespaces = list(itertools.islice(namespaces_iter, request_size))
# first and middle page condition
if len(namespaces) > page_size:
namespaces.pop(-1)
has_more_data = True
# middle page condition
if marker is not None:
has_prev_data = True
# first page condition when reached via prev back
elif sort_dir == 'desc' and marker is not None:
has_more_data = True
# last page condition
elif marker is not None:
has_prev_data = True
else:
namespaces = list(namespaces_iter)
namespaces = [Namespace(namespace) for namespace in namespaces]
return namespaces, has_more_data, has_prev_data |
0, module; 1, function_definition; 2, function_name:sort_js_files; 3, parameters; 4, block; 5, identifier:js_files; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, comment:"""Sorts JavaScript files in `js_files`.
It sorts JavaScript files in a given `js_files`
into source files, mock files and spec files based on file extension.
Output:
* sources: source files for production. The order of source files
is significant and should be listed in the below order:
- First, all the that defines the other application's angular module.
Those files have extension of `.module.js`. The order among them is
not significant.
- Followed by all other source code files. The order among them
is not significant.
* mocks: mock files provide mock data/services for tests. They have
extension of `.mock.js`. The order among them is not significant.
* specs: spec files for testing. They have extension of `.spec.js`.
The order among them is not significant.
"""; 14, assignment; 15, assignment; 16, assignment; 17, assignment; 18, assignment; 19, expression_list; 20, identifier:modules; 21, list_comprehension; 22, identifier:mocks; 23, list_comprehension; 24, identifier:specs; 25, list_comprehension; 26, identifier:other_sources; 27, list_comprehension; 28, identifier:sources; 29, binary_operator:modules + other_sources; 30, identifier:sources; 31, identifier:mocks; 32, identifier:specs; 33, identifier:f; 34, for_in_clause; 35, if_clause; 36, identifier:f; 37, for_in_clause; 38, if_clause; 39, identifier:f; 40, for_in_clause; 41, if_clause; 42, identifier:f; 43, for_in_clause; 44, if_clause; 45, identifier:modules; 46, identifier:other_sources; 47, identifier:f; 48, identifier:js_files; 49, call; 50, identifier:f; 51, identifier:js_files; 52, call; 53, identifier:f; 54, identifier:js_files; 55, call; 56, identifier:f; 57, identifier:js_files; 58, parenthesized_expression; 59, attribute; 60, argument_list; 61, attribute; 62, argument_list; 63, attribute; 64, argument_list; 65, boolean_operator; 66, identifier:f; 67, identifier:endswith; 68, identifier:MODULE_EXT; 69, identifier:f; 70, identifier:endswith; 71, identifier:MOCK_EXT; 72, identifier:f; 73, identifier:endswith; 74, identifier:SPEC_EXT; 75, boolean_operator; 76, not_operator; 77, not_operator; 78, not_operator; 79, call; 80, call; 81, call; 82, attribute; 83, argument_list; 84, attribute; 85, argument_list; 86, attribute; 87, argument_list; 88, identifier:f; 89, identifier:endswith; 90, identifier:SPEC_EXT; 91, identifier:f; 92, identifier:endswith; 93, identifier:MODULE_EXT; 94, identifier:f; 95, identifier:endswith; 96, identifier:MOCK_EXT | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 6, 13; 7, 14; 8, 15; 9, 16; 10, 17; 11, 18; 12, 19; 14, 20; 14, 21; 15, 22; 15, 23; 16, 24; 16, 25; 17, 26; 17, 27; 18, 28; 18, 29; 19, 30; 19, 31; 19, 32; 21, 33; 21, 34; 21, 35; 23, 36; 23, 37; 23, 38; 25, 39; 25, 40; 25, 41; 27, 42; 27, 43; 27, 44; 29, 45; 29, 46; 34, 47; 34, 48; 35, 49; 37, 50; 37, 51; 38, 52; 40, 53; 40, 54; 41, 55; 43, 56; 43, 57; 44, 58; 49, 59; 49, 60; 52, 61; 52, 62; 55, 63; 55, 64; 58, 65; 59, 66; 59, 67; 60, 68; 61, 69; 61, 70; 62, 71; 63, 72; 63, 73; 64, 74; 65, 75; 65, 76; 75, 77; 75, 78; 76, 79; 77, 80; 78, 81; 79, 82; 79, 83; 80, 84; 80, 85; 81, 86; 81, 87; 82, 88; 82, 89; 83, 90; 84, 91; 84, 92; 85, 93; 86, 94; 86, 95; 87, 96 | def sort_js_files(js_files):
"""Sorts JavaScript files in `js_files`.
It sorts JavaScript files in a given `js_files`
into source files, mock files and spec files based on file extension.
Output:
* sources: source files for production. The order of source files
is significant and should be listed in the below order:
- First, all the that defines the other application's angular module.
Those files have extension of `.module.js`. The order among them is
not significant.
- Followed by all other source code files. The order among them
is not significant.
* mocks: mock files provide mock data/services for tests. They have
extension of `.mock.js`. The order among them is not significant.
* specs: spec files for testing. They have extension of `.spec.js`.
The order among them is not significant.
"""
modules = [f for f in js_files if f.endswith(MODULE_EXT)]
mocks = [f for f in js_files if f.endswith(MOCK_EXT)]
specs = [f for f in js_files if f.endswith(SPEC_EXT)]
other_sources = [f for f in js_files
if (not f.endswith(MODULE_EXT) and
not f.endswith(MOCK_EXT) and
not f.endswith(SPEC_EXT))]
sources = modules + other_sources
return sources, mocks, specs |
0, module; 1, function_definition; 2, function_name:_slice_mostly_sorted; 3, parameters; 4, block; 5, identifier:array; 6, identifier:keep; 7, identifier:rest; 8, default_parameter; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, expression_statement; 15, expression_statement; 16, for_statement; 17, if_statement; 18, expression_statement; 19, return_statement; 20, identifier:ind; 21, None; 22, comment:"""Slice dask array `array` that is almost entirely sorted already.
We perform approximately `2 * len(keep)` slices on `array`.
This is OK, since `keep` is small. Individually, each of these slices
is entirely sorted.
Parameters
----------
array : dask.array.Array
keep : ndarray[Int]
This must be sorted.
rest : ndarray[Bool]
ind : ndarray[Int], optional
Returns
-------
sliced : dask.array.Array
"""; 23, comparison_operator:ind is None; 24, block; 25, assignment; 26, assignment; 27, comparison_operator:keep[0] > 0; 28, comment:# avoid creating empty slices; 29, block; 30, call; 31, assignment; 32, pattern_list; 33, identifier:windows; 34, block; 35, comparison_operator:keep[-1] < len(array) - 1; 36, comment:# avoid creating empty slices; 37, block; 38, assignment; 39, identifier:result; 40, identifier:ind; 41, None; 42, expression_statement; 43, identifier:idx; 44, call; 45, identifier:slices; 46, list; 47, subscript; 48, integer:0; 49, expression_statement; 50, attribute; 51, argument_list; 52, identifier:windows; 53, call; 54, identifier:l; 55, identifier:r; 56, if_statement; 57, expression_statement; 58, subscript; 59, binary_operator:len(array) - 1; 60, expression_statement; 61, identifier:result; 62, call; 63, assignment; 64, attribute; 65, argument_list; 66, identifier:keep; 67, integer:0; 68, call; 69, identifier:slices; 70, identifier:append; 71, list; 72, identifier:zip; 73, argument_list; 74, comparison_operator:r > l + 1; 75, comment:# avoid creating empty slices; 76, block; 77, call; 78, identifier:keep; 79, unary_operator; 80, call; 81, integer:1; 82, call; 83, attribute; 84, argument_list; 85, identifier:ind; 86, call; 87, identifier:np; 88, identifier:argsort; 89, call; 90, attribute; 91, argument_list; 92, subscript; 93, subscript; 94, subscript; 95, identifier:r; 96, binary_operator:l + 1; 97, expression_statement; 98, attribute; 99, argument_list; 100, integer:1; 101, identifier:len; 102, argument_list; 103, attribute; 104, argument_list; 105, identifier:da; 106, identifier:concatenate; 107, list_comprehension; 108, attribute; 109, argument_list; 110, attribute; 111, argument_list; 112, identifier:slices; 113, identifier:append; 114, call; 115, identifier:keep; 116, integer:0; 117, identifier:keep; 118, slice; 119, identifier:keep; 120, slice; 121, identifier:l; 122, integer:1; 123, call; 124, identifier:slices; 125, identifier:append; 126, list; 127, identifier:array; 128, identifier:slices; 129, identifier:append; 130, call; 131, subscript; 132, for_in_clause; 133, identifier:np; 134, identifier:arange; 135, call; 136, identifier:np; 137, identifier:concatenate; 138, list; 139, identifier:slice; 140, argument_list; 141, unary_operator; 142, integer:1; 143, attribute; 144, argument_list; 145, identifier:r; 146, identifier:slice; 147, argument_list; 148, identifier:array; 149, subscript; 150, identifier:slice_; 151, identifier:slices; 152, identifier:len; 153, argument_list; 154, identifier:keep; 155, subscript; 156, None; 157, subscript; 158, integer:1; 159, identifier:slices; 160, identifier:append; 161, call; 162, binary_operator:keep[-1] + 1; 163, None; 164, identifier:idx; 165, identifier:slice_; 166, identifier:array; 167, identifier:ind; 168, identifier:rest; 169, identifier:keep; 170, integer:0; 171, identifier:slice; 172, argument_list; 173, subscript; 174, integer:1; 175, binary_operator:l + 1; 176, identifier:r; 177, identifier:keep; 178, unary_operator; 179, identifier:l; 180, integer:1; 181, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 8, 20; 8, 21; 9, 22; 10, 23; 10, 24; 11, 25; 12, 26; 13, 27; 13, 28; 13, 29; 14, 30; 15, 31; 16, 32; 16, 33; 16, 34; 17, 35; 17, 36; 17, 37; 18, 38; 19, 39; 23, 40; 23, 41; 24, 42; 25, 43; 25, 44; 26, 45; 26, 46; 27, 47; 27, 48; 29, 49; 30, 50; 30, 51; 31, 52; 31, 53; 32, 54; 32, 55; 34, 56; 34, 57; 35, 58; 35, 59; 37, 60; 38, 61; 38, 62; 42, 63; 44, 64; 44, 65; 47, 66; 47, 67; 49, 68; 50, 69; 50, 70; 51, 71; 53, 72; 53, 73; 56, 74; 56, 75; 56, 76; 57, 77; 58, 78; 58, 79; 59, 80; 59, 81; 60, 82; 62, 83; 62, 84; 63, 85; 63, 86; 64, 87; 64, 88; 65, 89; 68, 90; 68, 91; 71, 92; 73, 93; 73, 94; 74, 95; 74, 96; 76, 97; 77, 98; 77, 99; 79, 100; 80, 101; 80, 102; 82, 103; 82, 104; 83, 105; 83, 106; 84, 107; 86, 108; 86, 109; 89, 110; 89, 111; 90, 112; 90, 113; 91, 114; 92, 115; 92, 116; 93, 117; 93, 118; 94, 119; 94, 120; 96, 121; 96, 122; 97, 123; 98, 124; 98, 125; 99, 126; 102, 127; 103, 128; 103, 129; 104, 130; 107, 131; 107, 132; 108, 133; 108, 134; 109, 135; 110, 136; 110, 137; 111, 138; 114, 139; 114, 140; 118, 141; 120, 142; 123, 143; 123, 144; 126, 145; 130, 146; 130, 147; 131, 148; 131, 149; 132, 150; 132, 151; 135, 152; 135, 153; 138, 154; 138, 155; 140, 156; 140, 157; 141, 158; 143, 159; 143, 160; 144, 161; 147, 162; 147, 163; 149, 164; 149, 165; 153, 166; 155, 167; 155, 168; 157, 169; 157, 170; 161, 171; 161, 172; 162, 173; 162, 174; 172, 175; 172, 176; 173, 177; 173, 178; 175, 179; 175, 180; 178, 181 | def _slice_mostly_sorted(array, keep, rest, ind=None):
"""Slice dask array `array` that is almost entirely sorted already.
We perform approximately `2 * len(keep)` slices on `array`.
This is OK, since `keep` is small. Individually, each of these slices
is entirely sorted.
Parameters
----------
array : dask.array.Array
keep : ndarray[Int]
This must be sorted.
rest : ndarray[Bool]
ind : ndarray[Int], optional
Returns
-------
sliced : dask.array.Array
"""
if ind is None:
ind = np.arange(len(array))
idx = np.argsort(np.concatenate([keep, ind[rest]]))
slices = []
if keep[0] > 0: # avoid creating empty slices
slices.append(slice(None, keep[0]))
slices.append([keep[0]])
windows = zip(keep[:-1], keep[1:])
for l, r in windows:
if r > l + 1: # avoid creating empty slices
slices.append(slice(l + 1, r))
slices.append([r])
if keep[-1] < len(array) - 1: # avoid creating empty slices
slices.append(slice(keep[-1] + 1, None))
result = da.concatenate([array[idx[slice_]] for slice_ in slices])
return result |
0, module; 1, function_definition; 2, function_name:sort_servers_closest; 3, parameters; 4, type; 5, block; 6, typed_parameter; 7, generic_type; 8, expression_statement; 9, if_statement; 10, expression_statement; 11, comment:# these tasks should never raise, returns None on errors; 12, expression_statement; 13, comment:# block and wait tasks; 14, expression_statement; 15, expression_statement; 16, return_statement; 17, identifier:servers; 18, type; 19, identifier:Sequence; 20, type_parameter; 21, comment:"""Sorts a list of servers by http round-trip time
Params:
servers: sequence of http server urls
Returns:
sequence of pairs of url,rtt in seconds, sorted by rtt, excluding failed servers
(possibly empty)
"""; 22, not_operator; 23, block; 24, assignment; 25, call; 26, assignment; 27, call; 28, identifier:sorted_servers; 29, generic_type; 30, type; 31, call; 32, raise_statement; 33, identifier:get_rtt_jobs; 34, call; 35, attribute; 36, argument_list; 37, identifier:sorted_servers; 38, type; 39, call; 40, attribute; 41, argument_list; 42, identifier:Sequence; 43, type_parameter; 44, generic_type; 45, attribute; 46, argument_list; 47, call; 48, identifier:set; 49, generator_expression; 50, identifier:gevent; 51, identifier:joinall; 52, identifier:get_rtt_jobs; 53, keyword_argument; 54, generic_type; 55, identifier:sorted; 56, argument_list; 57, identifier:log; 58, identifier:debug; 59, string; 60, keyword_argument; 61, type; 62, identifier:Tuple; 63, type_parameter; 64, set_comprehension; 65, identifier:issubset; 66, set; 67, identifier:TransportError; 68, argument_list; 69, call; 70, for_in_clause; 71, identifier:raise_error; 72, False; 73, identifier:List; 74, type_parameter; 75, generator_expression; 76, keyword_argument; 77, string_content:Matrix homeserver RTT times; 78, identifier:rtt_times; 79, identifier:sorted_servers; 80, identifier:str; 81, type; 82, type; 83, attribute; 84, for_in_clause; 85, string; 86, string; 87, string; 88, attribute; 89, argument_list; 90, identifier:server_url; 91, identifier:servers; 92, type; 93, attribute; 94, for_in_clause; 95, if_clause; 96, identifier:key; 97, call; 98, identifier:str; 99, identifier:float; 100, call; 101, identifier:scheme; 102, identifier:url; 103, identifier:servers; 104, string_content:http; 105, string_content:https; 106, string_content:Invalid server urls; 107, identifier:gevent; 108, identifier:spawn; 109, lambda; 110, identifier:server_url; 111, generic_type; 112, identifier:job; 113, identifier:value; 114, identifier:job; 115, identifier:get_rtt_jobs; 116, comparison_operator:job.value[1] is not None; 117, identifier:itemgetter; 118, argument_list; 119, identifier:urlparse; 120, argument_list; 121, lambda_parameters; 122, tuple; 123, identifier:Tuple; 124, type_parameter; 125, subscript; 126, None; 127, integer:1; 128, identifier:url; 129, identifier:url; 130, identifier:url; 131, call; 132, type; 133, type; 134, attribute; 135, integer:1; 136, identifier:get_http_rtt; 137, argument_list; 138, identifier:str; 139, identifier:float; 140, identifier:job; 141, identifier:value; 142, identifier:url | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 4, 7; 5, 8; 5, 9; 5, 10; 5, 11; 5, 12; 5, 13; 5, 14; 5, 15; 5, 16; 6, 17; 6, 18; 7, 19; 7, 20; 8, 21; 9, 22; 9, 23; 10, 24; 12, 25; 14, 26; 15, 27; 16, 28; 18, 29; 20, 30; 22, 31; 23, 32; 24, 33; 24, 34; 25, 35; 25, 36; 26, 37; 26, 38; 26, 39; 27, 40; 27, 41; 29, 42; 29, 43; 30, 44; 31, 45; 31, 46; 32, 47; 34, 48; 34, 49; 35, 50; 35, 51; 36, 52; 36, 53; 38, 54; 39, 55; 39, 56; 40, 57; 40, 58; 41, 59; 41, 60; 43, 61; 44, 62; 44, 63; 45, 64; 45, 65; 46, 66; 47, 67; 47, 68; 49, 69; 49, 70; 53, 71; 53, 72; 54, 73; 54, 74; 56, 75; 56, 76; 59, 77; 60, 78; 60, 79; 61, 80; 63, 81; 63, 82; 64, 83; 64, 84; 66, 85; 66, 86; 68, 87; 69, 88; 69, 89; 70, 90; 70, 91; 74, 92; 75, 93; 75, 94; 75, 95; 76, 96; 76, 97; 81, 98; 82, 99; 83, 100; 83, 101; 84, 102; 84, 103; 85, 104; 86, 105; 87, 106; 88, 107; 88, 108; 89, 109; 89, 110; 92, 111; 93, 112; 93, 113; 94, 114; 94, 115; 95, 116; 97, 117; 97, 118; 100, 119; 100, 120; 109, 121; 109, 122; 111, 123; 111, 124; 116, 125; 116, 126; 118, 127; 120, 128; 121, 129; 122, 130; 122, 131; 124, 132; 124, 133; 125, 134; 125, 135; 131, 136; 131, 137; 132, 138; 133, 139; 134, 140; 134, 141; 137, 142 | def sort_servers_closest(servers: Sequence[str]) -> Sequence[Tuple[str, float]]:
"""Sorts a list of servers by http round-trip time
Params:
servers: sequence of http server urls
Returns:
sequence of pairs of url,rtt in seconds, sorted by rtt, excluding failed servers
(possibly empty)
"""
if not {urlparse(url).scheme for url in servers}.issubset({'http', 'https'}):
raise TransportError('Invalid server urls')
get_rtt_jobs = set(
gevent.spawn(lambda url: (url, get_http_rtt(url)), server_url)
for server_url
in servers
)
# these tasks should never raise, returns None on errors
gevent.joinall(get_rtt_jobs, raise_error=False) # block and wait tasks
sorted_servers: List[Tuple[str, float]] = sorted(
(job.value for job in get_rtt_jobs if job.value[1] is not None),
key=itemgetter(1),
)
log.debug('Matrix homeserver RTT times', rtt_times=sorted_servers)
return sorted_servers |
0, module; 1, function_definition; 2, function_name:get_runs_by_id; 3, parameters; 4, block; 5, identifier:self; 6, identifier:config_id; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, for_statement; 11, expression_statement; 12, return_statement; 13, comment:"""
returns a list of runs for a given config id
The runs are sorted by ascending budget, so '-1' will give
the longest run for this config.
"""; 14, assignment; 15, assignment; 16, identifier:b; 17, call; 18, block; 19, call; 20, parenthesized_expression; 21, identifier:d; 22, subscript; 23, identifier:runs; 24, list; 25, attribute; 26, argument_list; 27, try_statement; 28, attribute; 29, argument_list; 30, identifier:runs; 31, attribute; 32, identifier:config_id; 33, attribute; 34, identifier:keys; 35, block; 36, except_clause; 37, identifier:runs; 38, identifier:sort; 39, keyword_argument; 40, identifier:self; 41, identifier:data; 42, identifier:d; 43, identifier:results; 44, expression_statement; 45, if_statement; 46, expression_statement; 47, block; 48, identifier:key; 49, lambda; 50, assignment; 51, comparison_operator:d.results[b] is None; 52, block; 53, else_clause; 54, call; 55, raise_statement; 56, lambda_parameters; 57, attribute; 58, identifier:err_logs; 59, call; 60, subscript; 61, None; 62, expression_statement; 63, block; 64, attribute; 65, argument_list; 66, identifier:r; 67, identifier:r; 68, identifier:budget; 69, attribute; 70, argument_list; 71, attribute; 72, identifier:b; 73, assignment; 74, expression_statement; 75, identifier:runs; 76, identifier:append; 77, identifier:r; 78, attribute; 79, identifier:get; 80, identifier:b; 81, None; 82, identifier:d; 83, identifier:results; 84, identifier:r; 85, call; 86, assignment; 87, identifier:d; 88, identifier:exceptions; 89, identifier:Run; 90, argument_list; 91, identifier:r; 92, call; 93, identifier:config_id; 94, identifier:b; 95, None; 96, None; 97, subscript; 98, identifier:err_logs; 99, identifier:Run; 100, argument_list; 101, attribute; 102, identifier:b; 103, identifier:config_id; 104, identifier:b; 105, subscript; 106, subscript; 107, subscript; 108, identifier:err_logs; 109, identifier:d; 110, identifier:time_stamps; 111, subscript; 112, string; 113, subscript; 114, string; 115, attribute; 116, identifier:b; 117, attribute; 118, identifier:b; 119, string_content:loss; 120, attribute; 121, identifier:b; 122, string_content:info; 123, identifier:d; 124, identifier:time_stamps; 125, identifier:d; 126, identifier:results; 127, identifier:d; 128, identifier:results | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 8, 14; 9, 15; 10, 16; 10, 17; 10, 18; 11, 19; 12, 20; 14, 21; 14, 22; 15, 23; 15, 24; 17, 25; 17, 26; 18, 27; 19, 28; 19, 29; 20, 30; 22, 31; 22, 32; 25, 33; 25, 34; 27, 35; 27, 36; 28, 37; 28, 38; 29, 39; 31, 40; 31, 41; 33, 42; 33, 43; 35, 44; 35, 45; 35, 46; 36, 47; 39, 48; 39, 49; 44, 50; 45, 51; 45, 52; 45, 53; 46, 54; 47, 55; 49, 56; 49, 57; 50, 58; 50, 59; 51, 60; 51, 61; 52, 62; 53, 63; 54, 64; 54, 65; 56, 66; 57, 67; 57, 68; 59, 69; 59, 70; 60, 71; 60, 72; 62, 73; 63, 74; 64, 75; 64, 76; 65, 77; 69, 78; 69, 79; 70, 80; 70, 81; 71, 82; 71, 83; 73, 84; 73, 85; 74, 86; 78, 87; 78, 88; 85, 89; 85, 90; 86, 91; 86, 92; 90, 93; 90, 94; 90, 95; 90, 96; 90, 97; 90, 98; 92, 99; 92, 100; 97, 101; 97, 102; 100, 103; 100, 104; 100, 105; 100, 106; 100, 107; 100, 108; 101, 109; 101, 110; 105, 111; 105, 112; 106, 113; 106, 114; 107, 115; 107, 116; 111, 117; 111, 118; 112, 119; 113, 120; 113, 121; 114, 122; 115, 123; 115, 124; 117, 125; 117, 126; 120, 127; 120, 128 | def get_runs_by_id(self, config_id):
"""
returns a list of runs for a given config id
The runs are sorted by ascending budget, so '-1' will give
the longest run for this config.
"""
d = self.data[config_id]
runs = []
for b in d.results.keys():
try:
err_logs = d.exceptions.get(b, None)
if d.results[b] is None:
r = Run(config_id, b, None, None , d.time_stamps[b], err_logs)
else:
r = Run(config_id, b, d.results[b]['loss'], d.results[b]['info'] , d.time_stamps[b], err_logs)
runs.append(r)
except:
raise
runs.sort(key=lambda r: r.budget)
return(runs) |
0, module; 1, function_definition; 2, function_name:spell; 3, parameters; 4, type; 5, block; 6, identifier:self; 7, typed_parameter; 8, generic_type; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, identifier:word; 15, type; 16, identifier:List; 17, type_parameter; 18, comment:"""
Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling
"""; 19, not_operator; 20, block; 21, assignment; 22, call; 23, identifier:candidates; 24, identifier:str; 25, type; 26, identifier:word; 27, return_statement; 28, identifier:candidates; 29, parenthesized_expression; 30, attribute; 31, argument_list; 32, identifier:str; 33, string:""; 34, boolean_operator; 35, identifier:candidates; 36, identifier:sort; 37, keyword_argument; 38, keyword_argument; 39, boolean_operator; 40, list; 41, identifier:key; 42, attribute; 43, identifier:reverse; 44, True; 45, boolean_operator; 46, call; 47, identifier:word; 48, identifier:self; 49, identifier:freq; 50, call; 51, call; 52, attribute; 53, argument_list; 54, attribute; 55, argument_list; 56, attribute; 57, argument_list; 58, identifier:self; 59, identifier:known; 60, call; 61, identifier:self; 62, identifier:known; 63, list; 64, identifier:self; 65, identifier:known; 66, call; 67, identifier:_edits2; 68, argument_list; 69, identifier:word; 70, identifier:_edits1; 71, argument_list; 72, identifier:word; 73, identifier:word | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 3, 7; 4, 8; 5, 9; 5, 10; 5, 11; 5, 12; 5, 13; 7, 14; 7, 15; 8, 16; 8, 17; 9, 18; 10, 19; 10, 20; 11, 21; 12, 22; 13, 23; 15, 24; 17, 25; 19, 26; 20, 27; 21, 28; 21, 29; 22, 30; 22, 31; 25, 32; 27, 33; 29, 34; 30, 35; 30, 36; 31, 37; 31, 38; 34, 39; 34, 40; 37, 41; 37, 42; 38, 43; 38, 44; 39, 45; 39, 46; 40, 47; 42, 48; 42, 49; 45, 50; 45, 51; 46, 52; 46, 53; 50, 54; 50, 55; 51, 56; 51, 57; 52, 58; 52, 59; 53, 60; 54, 61; 54, 62; 55, 63; 56, 64; 56, 65; 57, 66; 60, 67; 60, 68; 63, 69; 66, 70; 66, 71; 68, 72; 71, 73 | def spell(self, word: str) -> List[str]:
"""
Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling
"""
if not word:
return ""
candidates = (
self.known([word])
or self.known(_edits1(word))
or self.known(_edits2(word))
or [word]
)
candidates.sort(key=self.freq, reverse=True)
return candidates |
0, module; 1, function_definition; 2, function_name:rank; 3, parameters; 4, type; 5, block; 6, typed_parameter; 7, typed_default_parameter; 8, identifier:Counter; 9, expression_statement; 10, if_statement; 11, if_statement; 12, return_statement; 13, identifier:words; 14, type; 15, identifier:exclude_stopwords; 16, type; 17, False; 18, comment:"""
Sort words by frequency
:param list words: a list of words
:param bool exclude_stopwords: exclude stopwords
:return: Counter
"""; 19, not_operator; 20, block; 21, identifier:exclude_stopwords; 22, block; 23, call; 24, generic_type; 25, identifier:bool; 26, identifier:words; 27, return_statement; 28, expression_statement; 29, identifier:Counter; 30, argument_list; 31, identifier:List; 32, type_parameter; 33, None; 34, assignment; 35, identifier:words; 36, type; 37, identifier:words; 38, list_comprehension; 39, identifier:str; 40, identifier:word; 41, for_in_clause; 42, if_clause; 43, identifier:word; 44, identifier:words; 45, comparison_operator:word not in _STOPWORDS; 46, identifier:word; 47, identifier:_STOPWORDS | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 3, 7; 4, 8; 5, 9; 5, 10; 5, 11; 5, 12; 6, 13; 6, 14; 7, 15; 7, 16; 7, 17; 9, 18; 10, 19; 10, 20; 11, 21; 11, 22; 12, 23; 14, 24; 16, 25; 19, 26; 20, 27; 22, 28; 23, 29; 23, 30; 24, 31; 24, 32; 27, 33; 28, 34; 30, 35; 32, 36; 34, 37; 34, 38; 36, 39; 38, 40; 38, 41; 38, 42; 41, 43; 41, 44; 42, 45; 45, 46; 45, 47 | def rank(words: List[str], exclude_stopwords: bool = False) -> Counter:
"""
Sort words by frequency
:param list words: a list of words
:param bool exclude_stopwords: exclude stopwords
:return: Counter
"""
if not words:
return None
if exclude_stopwords:
words = [word for word in words if word not in _STOPWORDS]
return Counter(words) |
0, module; 1, function_definition; 2, function_name:iter; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, dictionary_splat_pattern; 10, expression_statement; 11, assert_statement; 12, if_statement; 13, expression_statement; 14, while_statement; 15, identifier:offset; 16, integer:0; 17, identifier:count; 18, None; 19, identifier:pagesize; 20, None; 21, identifier:kwargs; 22, comment:"""Iterates over the collection.
This method is equivalent to the :meth:`list` method, but
it returns an iterator and can load a certain number of entities at a
time from the server.
:param offset: The index of the first entity to return (optional).
:type offset: ``integer``
:param count: The maximum number of entities to return (optional).
:type count: ``integer``
:param pagesize: The number of entities to load (optional).
:type pagesize: ``integer``
:param kwargs: Additional arguments (optional):
- "search" (``string``): The search query to filter responses.
- "sort_dir" (``string``): The direction to sort returned items:
"asc" or "desc".
- "sort_key" (``string``): The field to use for sorting (optional).
- "sort_mode" (``string``): The collating sequence for sorting
returned items: "auto", "alpha", "alpha_case", or "num".
:type kwargs: ``dict``
**Example**::
import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
# Loads 10 saved searches at a time from the
# server.
...
"""; 23, boolean_operator; 24, comparison_operator:count is None; 25, block; 26, assignment; 27, boolean_operator; 28, block; 29, comparison_operator:pagesize is None; 30, comparison_operator:pagesize > 0; 31, identifier:count; 32, None; 33, expression_statement; 34, identifier:fetched; 35, integer:0; 36, comparison_operator:count == self.null_count; 37, comparison_operator:fetched < count; 38, expression_statement; 39, expression_statement; 40, expression_statement; 41, expression_statement; 42, for_statement; 43, if_statement; 44, expression_statement; 45, expression_statement; 46, identifier:pagesize; 47, None; 48, identifier:pagesize; 49, integer:0; 50, assignment; 51, identifier:count; 52, attribute; 53, identifier:fetched; 54, identifier:count; 55, assignment; 56, assignment; 57, assignment; 58, augmented_assignment; 59, identifier:item; 60, identifier:items; 61, block; 62, boolean_operator; 63, block; 64, augmented_assignment; 65, call; 66, identifier:count; 67, attribute; 68, identifier:self; 69, identifier:null_count; 70, identifier:response; 71, call; 72, identifier:items; 73, call; 74, identifier:N; 75, call; 76, identifier:fetched; 77, identifier:N; 78, expression_statement; 79, comparison_operator:pagesize is None; 80, comparison_operator:N < pagesize; 81, break_statement; 82, identifier:offset; 83, identifier:N; 84, attribute; 85, argument_list; 86, identifier:self; 87, identifier:null_count; 88, attribute; 89, argument_list; 90, attribute; 91, argument_list; 92, identifier:len; 93, argument_list; 94, yield; 95, identifier:pagesize; 96, None; 97, identifier:N; 98, identifier:pagesize; 99, identifier:logging; 100, identifier:debug; 101, string:"pagesize=%d, fetched=%d, offset=%d, N=%d, kwargs=%s"; 102, identifier:pagesize; 103, identifier:fetched; 104, identifier:offset; 105, identifier:N; 106, identifier:kwargs; 107, identifier:self; 108, identifier:get; 109, keyword_argument; 110, keyword_argument; 111, dictionary_splat; 112, identifier:self; 113, identifier:_load_list; 114, identifier:response; 115, identifier:items; 116, identifier:item; 117, identifier:count; 118, boolean_operator; 119, identifier:offset; 120, identifier:offset; 121, identifier:kwargs; 122, identifier:pagesize; 123, identifier:count | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 6, 15; 6, 16; 7, 17; 7, 18; 8, 19; 8, 20; 9, 21; 10, 22; 11, 23; 12, 24; 12, 25; 13, 26; 14, 27; 14, 28; 23, 29; 23, 30; 24, 31; 24, 32; 25, 33; 26, 34; 26, 35; 27, 36; 27, 37; 28, 38; 28, 39; 28, 40; 28, 41; 28, 42; 28, 43; 28, 44; 28, 45; 29, 46; 29, 47; 30, 48; 30, 49; 33, 50; 36, 51; 36, 52; 37, 53; 37, 54; 38, 55; 39, 56; 40, 57; 41, 58; 42, 59; 42, 60; 42, 61; 43, 62; 43, 63; 44, 64; 45, 65; 50, 66; 50, 67; 52, 68; 52, 69; 55, 70; 55, 71; 56, 72; 56, 73; 57, 74; 57, 75; 58, 76; 58, 77; 61, 78; 62, 79; 62, 80; 63, 81; 64, 82; 64, 83; 65, 84; 65, 85; 67, 86; 67, 87; 71, 88; 71, 89; 73, 90; 73, 91; 75, 92; 75, 93; 78, 94; 79, 95; 79, 96; 80, 97; 80, 98; 84, 99; 84, 100; 85, 101; 85, 102; 85, 103; 85, 104; 85, 105; 85, 106; 88, 107; 88, 108; 89, 109; 89, 110; 89, 111; 90, 112; 90, 113; 91, 114; 93, 115; 94, 116; 109, 117; 109, 118; 110, 119; 110, 120; 111, 121; 118, 122; 118, 123 | def iter(self, offset=0, count=None, pagesize=None, **kwargs):
"""Iterates over the collection.
This method is equivalent to the :meth:`list` method, but
it returns an iterator and can load a certain number of entities at a
time from the server.
:param offset: The index of the first entity to return (optional).
:type offset: ``integer``
:param count: The maximum number of entities to return (optional).
:type count: ``integer``
:param pagesize: The number of entities to load (optional).
:type pagesize: ``integer``
:param kwargs: Additional arguments (optional):
- "search" (``string``): The search query to filter responses.
- "sort_dir" (``string``): The direction to sort returned items:
"asc" or "desc".
- "sort_key" (``string``): The field to use for sorting (optional).
- "sort_mode" (``string``): The collating sequence for sorting
returned items: "auto", "alpha", "alpha_case", or "num".
:type kwargs: ``dict``
**Example**::
import splunklib.client as client
s = client.connect(...)
for saved_search in s.saved_searches.iter(pagesize=10):
# Loads 10 saved searches at a time from the
# server.
...
"""
assert pagesize is None or pagesize > 0
if count is None:
count = self.null_count
fetched = 0
while count == self.null_count or fetched < count:
response = self.get(count=pagesize or count, offset=offset, **kwargs)
items = self._load_list(response)
N = len(items)
fetched += N
for item in items:
yield item
if pagesize is None or N < pagesize:
break
offset += N
logging.debug("pagesize=%d, fetched=%d, offset=%d, N=%d, kwargs=%s", pagesize, fetched, offset, N, kwargs) |
0, module; 1, function_definition; 2, function_name:list; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, dictionary_splat_pattern; 8, expression_statement; 9, comment:# response = self.get(count=count, **kwargs); 10, comment:# return self._load_list(response); 11, return_statement; 12, identifier:count; 13, None; 14, identifier:kwargs; 15, comment:"""Retrieves a list of entities in this collection.
The entire collection is loaded at once and is returned as a list. This
function makes a single roundtrip to the server, plus at most two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
There is no caching--every call makes at least one round trip.
:param count: The maximum number of entities to return (optional).
:type count: ``integer``
:param kwargs: Additional arguments (optional):
- "offset" (``integer``): The offset of the first item to return.
- "search" (``string``): The search query to filter responses.
- "sort_dir" (``string``): The direction to sort returned items:
"asc" or "desc".
- "sort_key" (``string``): The field to use for sorting (optional).
- "sort_mode" (``string``): The collating sequence for sorting
returned items: "auto", "alpha", "alpha_case", or "num".
:type kwargs: ``dict``
:return: A ``list`` of entities.
"""; 16, call; 17, identifier:list; 18, argument_list; 19, call; 20, attribute; 21, argument_list; 22, identifier:self; 23, identifier:iter; 24, keyword_argument; 25, dictionary_splat; 26, identifier:count; 27, identifier:count; 28, identifier:kwargs | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 8, 15; 11, 16; 16, 17; 16, 18; 18, 19; 19, 20; 19, 21; 20, 22; 20, 23; 21, 24; 21, 25; 24, 26; 24, 27; 25, 28 | def list(self, count=None, **kwargs):
"""Retrieves a list of entities in this collection.
The entire collection is loaded at once and is returned as a list. This
function makes a single roundtrip to the server, plus at most two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
There is no caching--every call makes at least one round trip.
:param count: The maximum number of entities to return (optional).
:type count: ``integer``
:param kwargs: Additional arguments (optional):
- "offset" (``integer``): The offset of the first item to return.
- "search" (``string``): The search query to filter responses.
- "sort_dir" (``string``): The direction to sort returned items:
"asc" or "desc".
- "sort_key" (``string``): The field to use for sorting (optional).
- "sort_mode" (``string``): The collating sequence for sorting
returned items: "auto", "alpha", "alpha_case", or "num".
:type kwargs: ``dict``
:return: A ``list`` of entities.
"""
# response = self.get(count=count, **kwargs)
# return self._load_list(response)
return list(self.iter(count=count, **kwargs)) |
0, module; 1, function_definition; 2, function_name:query; 3, parameters; 4, block; 5, identifier:self; 6, dictionary_splat_pattern; 7, expression_statement; 8, return_statement; 9, identifier:query; 10, comment:"""
Gets the results of query, with optional parameters sort, limit, skip, and fields.
:param query: Optional parameters. Valid options are sort, limit, skip, and fields
:type query: ``dict``
:return: Array of documents retrieved by query.
:rtype: ``array``
"""; 11, call; 12, attribute; 13, argument_list; 14, identifier:json; 15, identifier:loads; 16, call; 17, attribute; 18, argument_list; 19, call; 20, identifier:decode; 21, string; 22, attribute; 23, argument_list; 24, string_content:utf-8; 25, attribute; 26, identifier:read; 27, call; 28, identifier:body; 29, attribute; 30, argument_list; 31, identifier:self; 32, identifier:_get; 33, string; 34, dictionary_splat; 35, identifier:query | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 6, 9; 7, 10; 8, 11; 11, 12; 11, 13; 12, 14; 12, 15; 13, 16; 16, 17; 16, 18; 17, 19; 17, 20; 18, 21; 19, 22; 19, 23; 21, 24; 22, 25; 22, 26; 25, 27; 25, 28; 27, 29; 27, 30; 29, 31; 29, 32; 30, 33; 30, 34; 34, 35 | def query(self, **query):
"""
Gets the results of query, with optional parameters sort, limit, skip, and fields.
:param query: Optional parameters. Valid options are sort, limit, skip, and fields
:type query: ``dict``
:return: Array of documents retrieved by query.
:rtype: ``array``
"""
return json.loads(self._get('', **query).body.read().decode('utf-8')) |
0, module; 1, function_definition; 2, function_name:query; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, dictionary_splat_pattern; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, return_statement; 21, identifier:area; 22, None; 23, identifier:date; 24, None; 25, identifier:raw; 26, None; 27, identifier:area_relation; 28, string; 29, identifier:order_by; 30, None; 31, identifier:limit; 32, None; 33, identifier:offset; 34, integer:0; 35, identifier:keywords; 36, comment:"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""; 37, assignment; 38, call; 39, assignment; 40, assignment; 41, call; 42, call; 43, string_content:Intersects; 44, identifier:query; 45, call; 46, attribute; 47, argument_list; 48, identifier:formatted_order_by; 49, call; 50, pattern_list; 51, call; 52, attribute; 53, argument_list; 54, identifier:_parse_opensearch_response; 55, argument_list; 56, attribute; 57, argument_list; 58, attribute; 59, identifier:debug; 60, string:"Running query: order_by=%s, limit=%s, offset=%s, query=%s"; 61, identifier:order_by; 62, identifier:limit; 63, identifier:offset; 64, identifier:query; 65, identifier:_format_order_by; 66, argument_list; 67, identifier:response; 68, identifier:count; 69, attribute; 70, argument_list; 71, attribute; 72, identifier:info; 73, string:"Found %s products"; 74, identifier:count; 75, identifier:response; 76, identifier:self; 77, identifier:format_query; 78, identifier:area; 79, identifier:date; 80, identifier:raw; 81, identifier:area_relation; 82, dictionary_splat; 83, identifier:self; 84, identifier:logger; 85, identifier:order_by; 86, identifier:self; 87, identifier:_load_query; 88, identifier:query; 89, identifier:formatted_order_by; 90, identifier:limit; 91, identifier:offset; 92, identifier:self; 93, identifier:logger; 94, identifier:keywords | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 6, 21; 6, 22; 7, 23; 7, 24; 8, 25; 8, 26; 9, 27; 9, 28; 10, 29; 10, 30; 11, 31; 11, 32; 12, 33; 12, 34; 13, 35; 14, 36; 15, 37; 16, 38; 17, 39; 18, 40; 19, 41; 20, 42; 28, 43; 37, 44; 37, 45; 38, 46; 38, 47; 39, 48; 39, 49; 40, 50; 40, 51; 41, 52; 41, 53; 42, 54; 42, 55; 45, 56; 45, 57; 46, 58; 46, 59; 47, 60; 47, 61; 47, 62; 47, 63; 47, 64; 49, 65; 49, 66; 50, 67; 50, 68; 51, 69; 51, 70; 52, 71; 52, 72; 53, 73; 53, 74; 55, 75; 56, 76; 56, 77; 57, 78; 57, 79; 57, 80; 57, 81; 57, 82; 58, 83; 58, 84; 66, 85; 69, 86; 69, 87; 70, 88; 70, 89; 70, 90; 70, 91; 71, 92; 71, 93; 82, 94 | def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
query = self.format_query(area, date, raw, area_relation, **keywords)
self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s",
order_by, limit, offset, query)
formatted_order_by = _format_order_by(order_by)
response, count = self._load_query(query, formatted_order_by, limit, offset)
self.logger.info("Found %s products", count)
return _parse_opensearch_response(response) |
0, module; 1, function_definition; 2, function_name:get_suggested_type_names; 3, parameters; 4, block; 5, identifier:schema; 6, identifier:output_type; 7, identifier:field_name; 8, expression_statement; 9, if_statement; 10, comment:# Otherwise, must be an Object type, which does not have possible fields.; 11, return_statement; 12, comment:"""Go through all of the implementations of type, as well as the interfaces
that they implement. If any of those types include the provided field,
suggest them, sorted by how often the type is referenced, starting
with Interfaces."""; 13, call; 14, block; 15, list; 16, identifier:isinstance; 17, argument_list; 18, expression_statement; 19, expression_statement; 20, for_statement; 21, comment:# Suggest interface types based on how common they are.; 22, expression_statement; 23, comment:# Suggest both interface and object types.; 24, expression_statement; 25, return_statement; 26, identifier:output_type; 27, tuple; 28, assignment; 29, assignment; 30, identifier:possible_type; 31, call; 32, block; 33, assignment; 34, call; 35, identifier:suggested_interface_types; 36, identifier:GraphQLInterfaceType; 37, identifier:GraphQLUnionType; 38, identifier:suggested_object_types; 39, list; 40, identifier:interface_usage_count; 41, call; 42, attribute; 43, argument_list; 44, if_statement; 45, comment:# This object type defines this field.; 46, expression_statement; 47, for_statement; 48, identifier:suggested_interface_types; 49, call; 50, attribute; 51, argument_list; 52, identifier:OrderedDict; 53, argument_list; 54, identifier:schema; 55, identifier:get_possible_types; 56, identifier:output_type; 57, not_operator; 58, block; 59, call; 60, identifier:possible_interface; 61, attribute; 62, block; 63, identifier:sorted; 64, argument_list; 65, identifier:suggested_interface_types; 66, identifier:extend; 67, identifier:suggested_object_types; 68, call; 69, return_statement; 70, attribute; 71, argument_list; 72, identifier:possible_type; 73, identifier:interfaces; 74, if_statement; 75, comment:# This interface type defines this field.; 76, expression_statement; 77, call; 78, keyword_argument; 79, keyword_argument; 80, attribute; 81, argument_list; 82, identifier:suggested_object_types; 83, identifier:append; 84, attribute; 85, not_operator; 86, block; 87, assignment; 88, identifier:list; 89, argument_list; 90, identifier:key; 91, lambda; 92, identifier:reverse; 93, True; 94, attribute; 95, identifier:get; 96, identifier:field_name; 97, identifier:possible_type; 98, identifier:name; 99, call; 100, continue_statement; 101, subscript; 102, parenthesized_expression; 103, call; 104, lambda_parameters; 105, subscript; 106, identifier:possible_type; 107, identifier:fields; 108, attribute; 109, argument_list; 110, identifier:interface_usage_count; 111, attribute; 112, binary_operator:interface_usage_count.get(possible_interface.name, 0) + 1; 113, attribute; 114, argument_list; 115, identifier:k; 116, identifier:interface_usage_count; 117, identifier:k; 118, attribute; 119, identifier:get; 120, identifier:field_name; 121, identifier:possible_interface; 122, identifier:name; 123, call; 124, integer:1; 125, identifier:interface_usage_count; 126, identifier:keys; 127, identifier:possible_interface; 128, identifier:fields; 129, attribute; 130, argument_list; 131, identifier:interface_usage_count; 132, identifier:get; 133, attribute; 134, integer:0; 135, identifier:possible_interface; 136, identifier:name | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 8, 12; 9, 13; 9, 14; 11, 15; 13, 16; 13, 17; 14, 18; 14, 19; 14, 20; 14, 21; 14, 22; 14, 23; 14, 24; 14, 25; 17, 26; 17, 27; 18, 28; 19, 29; 20, 30; 20, 31; 20, 32; 22, 33; 24, 34; 25, 35; 27, 36; 27, 37; 28, 38; 28, 39; 29, 40; 29, 41; 31, 42; 31, 43; 32, 44; 32, 45; 32, 46; 32, 47; 33, 48; 33, 49; 34, 50; 34, 51; 41, 52; 41, 53; 42, 54; 42, 55; 43, 56; 44, 57; 44, 58; 46, 59; 47, 60; 47, 61; 47, 62; 49, 63; 49, 64; 50, 65; 50, 66; 51, 67; 57, 68; 58, 69; 59, 70; 59, 71; 61, 72; 61, 73; 62, 74; 62, 75; 62, 76; 64, 77; 64, 78; 64, 79; 68, 80; 68, 81; 70, 82; 70, 83; 71, 84; 74, 85; 74, 86; 76, 87; 77, 88; 77, 89; 78, 90; 78, 91; 79, 92; 79, 93; 80, 94; 80, 95; 81, 96; 84, 97; 84, 98; 85, 99; 86, 100; 87, 101; 87, 102; 89, 103; 91, 104; 91, 105; 94, 106; 94, 107; 99, 108; 99, 109; 101, 110; 101, 111; 102, 112; 103, 113; 103, 114; 104, 115; 105, 116; 105, 117; 108, 118; 108, 119; 109, 120; 111, 121; 111, 122; 112, 123; 112, 124; 113, 125; 113, 126; 118, 127; 118, 128; 123, 129; 123, 130; 129, 131; 129, 132; 130, 133; 130, 134; 133, 135; 133, 136 | def get_suggested_type_names(schema, output_type, field_name):
"""Go through all of the implementations of type, as well as the interfaces
that they implement. If any of those types include the provided field,
suggest them, sorted by how often the type is referenced, starting
with Interfaces."""
if isinstance(output_type, (GraphQLInterfaceType, GraphQLUnionType)):
suggested_object_types = []
interface_usage_count = OrderedDict()
for possible_type in schema.get_possible_types(output_type):
if not possible_type.fields.get(field_name):
return
# This object type defines this field.
suggested_object_types.append(possible_type.name)
for possible_interface in possible_type.interfaces:
if not possible_interface.fields.get(field_name):
continue
# This interface type defines this field.
interface_usage_count[possible_interface.name] = (
interface_usage_count.get(possible_interface.name, 0) + 1
)
# Suggest interface types based on how common they are.
suggested_interface_types = sorted(
list(interface_usage_count.keys()),
key=lambda k: interface_usage_count[k],
reverse=True,
)
# Suggest both interface and object types.
suggested_interface_types.extend(suggested_object_types)
return suggested_interface_types
# Otherwise, must be an Object type, which does not have possible fields.
return [] |
0, module; 1, function_definition; 2, function_name:suggestion_list; 3, parameters; 4, block; 5, identifier:inp; 6, identifier:options; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, for_statement; 11, return_statement; 12, comment:"""
Given an invalid input string and a list of valid options, returns a filtered
list of valid options sorted based on their similarity with the input.
"""; 13, assignment; 14, assignment; 15, identifier:option; 16, identifier:options; 17, block; 18, call; 19, identifier:options_by_distance; 20, call; 21, identifier:input_threshold; 22, binary_operator:len(inp) / 2; 23, expression_statement; 24, expression_statement; 25, if_statement; 26, identifier:sorted; 27, argument_list; 28, identifier:OrderedDict; 29, argument_list; 30, call; 31, integer:2; 32, assignment; 33, assignment; 34, comparison_operator:distance <= threshold; 35, block; 36, call; 37, keyword_argument; 38, identifier:len; 39, argument_list; 40, identifier:distance; 41, call; 42, identifier:threshold; 43, call; 44, identifier:distance; 45, identifier:threshold; 46, expression_statement; 47, identifier:list; 48, argument_list; 49, identifier:key; 50, lambda; 51, identifier:inp; 52, identifier:lexical_distance; 53, argument_list; 54, identifier:max; 55, argument_list; 56, assignment; 57, call; 58, lambda_parameters; 59, subscript; 60, identifier:inp; 61, identifier:option; 62, identifier:input_threshold; 63, binary_operator:len(option) / 2; 64, integer:1; 65, subscript; 66, identifier:distance; 67, attribute; 68, argument_list; 69, identifier:k; 70, identifier:options_by_distance; 71, identifier:k; 72, call; 73, integer:2; 74, identifier:options_by_distance; 75, identifier:option; 76, identifier:options_by_distance; 77, identifier:keys; 78, identifier:len; 79, argument_list; 80, identifier:option | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 7, 12; 8, 13; 9, 14; 10, 15; 10, 16; 10, 17; 11, 18; 13, 19; 13, 20; 14, 21; 14, 22; 17, 23; 17, 24; 17, 25; 18, 26; 18, 27; 20, 28; 20, 29; 22, 30; 22, 31; 23, 32; 24, 33; 25, 34; 25, 35; 27, 36; 27, 37; 30, 38; 30, 39; 32, 40; 32, 41; 33, 42; 33, 43; 34, 44; 34, 45; 35, 46; 36, 47; 36, 48; 37, 49; 37, 50; 39, 51; 41, 52; 41, 53; 43, 54; 43, 55; 46, 56; 48, 57; 50, 58; 50, 59; 53, 60; 53, 61; 55, 62; 55, 63; 55, 64; 56, 65; 56, 66; 57, 67; 57, 68; 58, 69; 59, 70; 59, 71; 63, 72; 63, 73; 65, 74; 65, 75; 67, 76; 67, 77; 72, 78; 72, 79; 79, 80 | def suggestion_list(inp, options):
"""
Given an invalid input string and a list of valid options, returns a filtered
list of valid options sorted based on their similarity with the input.
"""
options_by_distance = OrderedDict()
input_threshold = len(inp) / 2
for option in options:
distance = lexical_distance(inp, option)
threshold = max(input_threshold, len(option) / 2, 1)
if distance <= threshold:
options_by_distance[option] = distance
return sorted(
list(options_by_distance.keys()), key=lambda k: options_by_distance[k]
) |
0, module; 1, function_definition; 2, function_name:lexical_distance; 3, parameters; 4, block; 5, identifier:a; 6, identifier:b; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, for_statement; 11, for_statement; 12, return_statement; 13, comment:"""
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
This distance can be useful for detecting typos in input or sorting
@returns distance in number of edits
"""; 14, assignment; 15, assignment; 16, identifier:i; 17, call; 18, block; 19, identifier:i; 20, call; 21, block; 22, subscript; 23, identifier:d; 24, boolean_operator; 25, identifier:d_len; 26, boolean_operator; 27, identifier:range; 28, argument_list; 29, for_statement; 30, identifier:range; 31, argument_list; 32, for_statement; 33, subscript; 34, call; 35, list_comprehension; 36, list; 37, call; 38, integer:1; 39, identifier:d_len; 40, identifier:j; 41, call; 42, block; 43, integer:1; 44, binary_operator:len(a) + 1; 45, identifier:j; 46, call; 47, block; 48, identifier:d; 49, call; 50, identifier:len; 51, argument_list; 52, list; 53, for_in_clause; 54, identifier:len; 55, argument_list; 56, identifier:range; 57, argument_list; 58, if_statement; 59, call; 60, integer:1; 61, identifier:range; 62, argument_list; 63, expression_statement; 64, expression_statement; 65, if_statement; 66, identifier:len; 67, argument_list; 68, identifier:b; 69, identifier:i; 70, identifier:i; 71, call; 72, identifier:d; 73, integer:1; 74, binary_operator:len(b) + 1; 75, comparison_operator:i == 0; 76, block; 77, else_clause; 78, identifier:len; 79, argument_list; 80, integer:1; 81, binary_operator:len(b) + 1; 82, assignment; 83, assignment; 84, boolean_operator; 85, block; 86, identifier:a; 87, identifier:range; 88, argument_list; 89, call; 90, integer:1; 91, identifier:i; 92, integer:0; 93, expression_statement; 94, block; 95, identifier:a; 96, call; 97, integer:1; 98, identifier:cost; 99, conditional_expression:0 if a[i - 1] == b[j - 1] else 1; 100, subscript; 101, call; 102, boolean_operator; 103, comparison_operator:a[i - 2] == b[j - 1]; 104, expression_statement; 105, binary_operator:len(a) + 1; 106, identifier:len; 107, argument_list; 108, call; 109, expression_statement; 110, identifier:len; 111, argument_list; 112, integer:0; 113, comparison_operator:a[i - 1] == b[j - 1]; 114, integer:1; 115, subscript; 116, identifier:j; 117, identifier:min; 118, argument_list; 119, boolean_operator; 120, comparison_operator:a[i - 1] == b[j - 2]; 121, subscript; 122, subscript; 123, assignment; 124, call; 125, integer:1; 126, identifier:b; 127, attribute; 128, argument_list; 129, call; 130, identifier:b; 131, subscript; 132, subscript; 133, identifier:d; 134, identifier:i; 135, binary_operator:d[i - 1][j] + 1; 136, binary_operator:d[i][j - 1] + 1; 137, binary_operator:d[i - 1][j - 1] + cost; 138, comparison_operator:i > 1; 139, comparison_operator:j < 1; 140, subscript; 141, subscript; 142, identifier:a; 143, binary_operator:i - 2; 144, identifier:b; 145, binary_operator:j - 1; 146, subscript; 147, call; 148, identifier:len; 149, argument_list; 150, subscript; 151, identifier:append; 152, identifier:j; 153, attribute; 154, argument_list; 155, identifier:a; 156, binary_operator:i - 1; 157, identifier:b; 158, binary_operator:j - 1; 159, subscript; 160, integer:1; 161, subscript; 162, integer:1; 163, subscript; 164, identifier:cost; 165, identifier:i; 166, integer:1; 167, identifier:j; 168, integer:1; 169, identifier:a; 170, binary_operator:i - 1; 171, identifier:b; 172, binary_operator:j - 2; 173, identifier:i; 174, integer:2; 175, identifier:j; 176, integer:1; 177, subscript; 178, identifier:j; 179, identifier:min; 180, argument_list; 181, identifier:a; 182, identifier:d; 183, identifier:i; 184, subscript; 185, identifier:append; 186, integer:0; 187, identifier:i; 188, integer:1; 189, identifier:j; 190, integer:1; 191, subscript; 192, identifier:j; 193, subscript; 194, binary_operator:j - 1; 195, subscript; 196, binary_operator:j - 1; 197, identifier:i; 198, integer:1; 199, identifier:j; 200, integer:2; 201, identifier:d; 202, identifier:i; 203, subscript; 204, binary_operator:d[i - 2][j - 2] + cost; 205, identifier:d; 206, identifier:i; 207, identifier:d; 208, binary_operator:i - 1; 209, identifier:d; 210, identifier:i; 211, identifier:j; 212, integer:1; 213, identifier:d; 214, binary_operator:i - 1; 215, identifier:j; 216, integer:1; 217, subscript; 218, identifier:j; 219, subscript; 220, identifier:cost; 221, identifier:i; 222, integer:1; 223, identifier:i; 224, integer:1; 225, identifier:d; 226, identifier:i; 227, subscript; 228, binary_operator:j - 2; 229, identifier:d; 230, binary_operator:i - 2; 231, identifier:j; 232, integer:2; 233, identifier:i; 234, integer:2 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 8, 14; 9, 15; 10, 16; 10, 17; 10, 18; 11, 19; 11, 20; 11, 21; 12, 22; 14, 23; 14, 24; 15, 25; 15, 26; 17, 27; 17, 28; 18, 29; 20, 30; 20, 31; 21, 32; 22, 33; 22, 34; 24, 35; 24, 36; 26, 37; 26, 38; 28, 39; 29, 40; 29, 41; 29, 42; 31, 43; 31, 44; 32, 45; 32, 46; 32, 47; 33, 48; 33, 49; 34, 50; 34, 51; 35, 52; 35, 53; 37, 54; 37, 55; 41, 56; 41, 57; 42, 58; 44, 59; 44, 60; 46, 61; 46, 62; 47, 63; 47, 64; 47, 65; 49, 66; 49, 67; 51, 68; 52, 69; 53, 70; 53, 71; 55, 72; 57, 73; 57, 74; 58, 75; 58, 76; 58, 77; 59, 78; 59, 79; 62, 80; 62, 81; 63, 82; 64, 83; 65, 84; 65, 85; 67, 86; 71, 87; 71, 88; 74, 89; 74, 90; 75, 91; 75, 92; 76, 93; 77, 94; 79, 95; 81, 96; 81, 97; 82, 98; 82, 99; 83, 100; 83, 101; 84, 102; 84, 103; 85, 104; 88, 105; 89, 106; 89, 107; 93, 108; 94, 109; 96, 110; 96, 111; 99, 112; 99, 113; 99, 114; 100, 115; 100, 116; 101, 117; 101, 118; 102, 119; 102, 120; 103, 121; 103, 122; 104, 123; 105, 124; 105, 125; 107, 126; 108, 127; 108, 128; 109, 129; 111, 130; 113, 131; 113, 132; 115, 133; 115, 134; 118, 135; 118, 136; 118, 137; 119, 138; 119, 139; 120, 140; 120, 141; 121, 142; 121, 143; 122, 144; 122, 145; 123, 146; 123, 147; 124, 148; 124, 149; 127, 150; 127, 151; 128, 152; 129, 153; 129, 154; 131, 155; 131, 156; 132, 157; 132, 158; 135, 159; 135, 160; 136, 161; 136, 162; 137, 163; 137, 164; 138, 165; 138, 166; 139, 167; 139, 168; 140, 169; 140, 170; 141, 171; 141, 172; 143, 173; 143, 174; 145, 175; 145, 176; 146, 177; 146, 178; 147, 179; 147, 180; 149, 181; 150, 182; 150, 183; 153, 184; 153, 185; 154, 186; 156, 187; 156, 188; 158, 189; 158, 190; 159, 191; 159, 192; 161, 193; 161, 194; 163, 195; 163, 196; 170, 197; 170, 198; 172, 199; 172, 200; 177, 201; 177, 202; 180, 203; 180, 204; 184, 205; 184, 206; 191, 207; 191, 208; 193, 209; 193, 210; 194, 211; 194, 212; 195, 213; 195, 214; 196, 215; 196, 216; 203, 217; 203, 218; 204, 219; 204, 220; 208, 221; 208, 222; 214, 223; 214, 224; 217, 225; 217, 226; 219, 227; 219, 228; 227, 229; 227, 230; 228, 231; 228, 232; 230, 233; 230, 234 | def lexical_distance(a, b):
"""
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
This distance can be useful for detecting typos in input or sorting
@returns distance in number of edits
"""
d = [[i] for i in range(len(a) + 1)] or []
d_len = len(d) or 1
for i in range(d_len):
for j in range(1, len(b) + 1):
if i == 0:
d[i].append(j)
else:
d[i].append(0)
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
if i > 1 and j < 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost)
return d[len(a)][len(b)] |
0, module; 1, function_definition; 2, function_name:arrange; 3, parameters; 4, block; 5, identifier:df; 6, list_splat_pattern; 7, dictionary_splat_pattern; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, identifier:args; 15, identifier:kwargs; 16, comment:"""Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in arrange).
Args:
*args: Symbolic, string, integer or lists of those types indicating
columns to sort the DataFrame by.
Kwargs:
**kwargs: Any keyword arguments will be passed through to the pandas
`DataFrame.sort_values` function.
"""; 17, assignment; 18, assignment; 19, assignment; 20, assignment; 21, subscript; 22, identifier:flat_args; 23, list_comprehension; 24, identifier:series; 25, list_comprehension; 26, identifier:sorter; 27, call; 28, identifier:sorter; 29, call; 30, attribute; 31, attribute; 32, slice; 33, identifier:a; 34, for_in_clause; 35, conditional_expression:df[arg] if isinstance(arg, str) else
df.iloc[:, arg] if isinstance(arg, int) else
pd.Series(arg); 36, for_in_clause; 37, attribute; 38, argument_list; 39, attribute; 40, argument_list; 41, identifier:df; 42, identifier:iloc; 43, identifier:sorter; 44, identifier:index; 45, identifier:a; 46, call; 47, subscript; 48, call; 49, conditional_expression:df.iloc[:, arg] if isinstance(arg, int) else
pd.Series(arg); 50, identifier:arg; 51, identifier:flat_args; 52, call; 53, identifier:reset_index; 54, keyword_argument; 55, identifier:sorter; 56, identifier:sort_values; 57, call; 58, dictionary_splat; 59, identifier:flatten; 60, argument_list; 61, identifier:df; 62, identifier:arg; 63, identifier:isinstance; 64, argument_list; 65, subscript; 66, call; 67, call; 68, attribute; 69, argument_list; 70, identifier:drop; 71, True; 72, attribute; 73, argument_list; 74, identifier:kwargs; 75, identifier:args; 76, identifier:arg; 77, identifier:str; 78, attribute; 79, slice; 80, identifier:arg; 81, identifier:isinstance; 82, argument_list; 83, attribute; 84, argument_list; 85, identifier:pd; 86, identifier:concat; 87, identifier:series; 88, keyword_argument; 89, attribute; 90, identifier:tolist; 91, identifier:df; 92, identifier:iloc; 93, identifier:arg; 94, identifier:int; 95, identifier:pd; 96, identifier:Series; 97, identifier:arg; 98, identifier:axis; 99, integer:1; 100, identifier:sorter; 101, identifier:columns | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 7, 15; 8, 16; 9, 17; 10, 18; 11, 19; 12, 20; 13, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 19, 27; 20, 28; 20, 29; 21, 30; 21, 31; 21, 32; 23, 33; 23, 34; 25, 35; 25, 36; 27, 37; 27, 38; 29, 39; 29, 40; 30, 41; 30, 42; 31, 43; 31, 44; 34, 45; 34, 46; 35, 47; 35, 48; 35, 49; 36, 50; 36, 51; 37, 52; 37, 53; 38, 54; 39, 55; 39, 56; 40, 57; 40, 58; 46, 59; 46, 60; 47, 61; 47, 62; 48, 63; 48, 64; 49, 65; 49, 66; 49, 67; 52, 68; 52, 69; 54, 70; 54, 71; 57, 72; 57, 73; 58, 74; 60, 75; 64, 76; 64, 77; 65, 78; 65, 79; 65, 80; 66, 81; 66, 82; 67, 83; 67, 84; 68, 85; 68, 86; 69, 87; 69, 88; 72, 89; 72, 90; 78, 91; 78, 92; 82, 93; 82, 94; 83, 95; 83, 96; 84, 97; 88, 98; 88, 99; 89, 100; 89, 101 | def arrange(df, *args, **kwargs):
"""Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in arrange).
Args:
*args: Symbolic, string, integer or lists of those types indicating
columns to sort the DataFrame by.
Kwargs:
**kwargs: Any keyword arguments will be passed through to the pandas
`DataFrame.sort_values` function.
"""
flat_args = [a for a in flatten(args)]
series = [df[arg] if isinstance(arg, str) else
df.iloc[:, arg] if isinstance(arg, int) else
pd.Series(arg) for arg in flat_args]
sorter = pd.concat(series, axis=1).reset_index(drop=True)
sorter = sorter.sort_values(sorter.columns.tolist(), **kwargs)
return df.iloc[sorter.index, :] |
0, module; 1, function_definition; 2, function_name:csort; 3, parameters; 4, block; 5, identifier:objs; 6, identifier:key; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, comment:"""Order-preserving sorting function."""; 11, assignment; 12, call; 13, identifier:idxs; 14, call; 15, identifier:sorted; 16, argument_list; 17, identifier:dict; 18, generator_expression; 19, identifier:objs; 20, keyword_argument; 21, tuple; 22, for_in_clause; 23, identifier:key; 24, lambda; 25, identifier:obj; 26, identifier:i; 27, tuple_pattern; 28, call; 29, lambda_parameters; 30, tuple; 31, identifier:i; 32, identifier:obj; 33, identifier:enumerate; 34, argument_list; 35, identifier:obj; 36, call; 37, subscript; 38, identifier:objs; 39, identifier:key; 40, argument_list; 41, identifier:idxs; 42, identifier:obj; 43, identifier:obj | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 9, 12; 11, 13; 11, 14; 12, 15; 12, 16; 14, 17; 14, 18; 16, 19; 16, 20; 18, 21; 18, 22; 20, 23; 20, 24; 21, 25; 21, 26; 22, 27; 22, 28; 24, 29; 24, 30; 27, 31; 27, 32; 28, 33; 28, 34; 29, 35; 30, 36; 30, 37; 34, 38; 36, 39; 36, 40; 37, 41; 37, 42; 40, 43 | def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) |
0, module; 1, function_definition; 2, function_name:fast_combine_pairs; 3, parameters; 4, block; 5, identifier:files; 6, identifier:force_single; 7, identifier:full_name; 8, identifier:separators; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, comment:# for each file, save the longest pair it is in; 16, for_statement; 17, comment:# keep only unique pairs; 18, expression_statement; 19, comment:# ensure filenames are R1 followed by R2; 20, return_statement; 21, comment:"""
assume files that need to be paired are within 10 entries of each other, once the list is sorted
"""; 22, assignment; 23, assignment; 24, assignment; 25, assignment; 26, assignment; 27, identifier:pair; 28, identifier:pairs; 29, block; 30, assignment; 31, list_comprehension; 32, identifier:files; 33, call; 34, identifier:chunks; 35, call; 36, identifier:pairs; 37, list_comprehension; 38, identifier:pairs; 39, list_comprehension; 40, identifier:longest; 41, call; 42, for_statement; 43, identifier:longest; 44, set_comprehension; 45, call; 46, for_in_clause; 47, identifier:sort_filenames; 48, argument_list; 49, attribute; 50, argument_list; 51, call; 52, for_in_clause; 53, identifier:y; 54, for_in_clause; 55, for_in_clause; 56, identifier:defaultdict; 57, argument_list; 58, identifier:file; 59, identifier:pair; 60, block; 61, call; 62, for_in_clause; 63, identifier:sort_filenames; 64, argument_list; 65, identifier:x; 66, identifier:longest; 67, identifier:files; 68, identifier:tz; 69, identifier:sliding_window; 70, integer:10; 71, identifier:files; 72, identifier:combine_pairs; 73, argument_list; 74, identifier:chunk; 75, identifier:chunks; 76, identifier:x; 77, identifier:pairs; 78, identifier:y; 79, identifier:x; 80, identifier:list; 81, if_statement; 82, identifier:tuple; 83, argument_list; 84, identifier:x; 85, call; 86, call; 87, identifier:chunk; 88, identifier:force_single; 89, identifier:full_name; 90, identifier:separators; 91, comparison_operator:len(longest[file]) < len(pair); 92, block; 93, call; 94, attribute; 95, argument_list; 96, identifier:list; 97, argument_list; 98, call; 99, call; 100, expression_statement; 101, identifier:sort_filenames; 102, argument_list; 103, identifier:longest; 104, identifier:values; 105, identifier:x; 106, identifier:len; 107, argument_list; 108, identifier:len; 109, argument_list; 110, assignment; 111, identifier:x; 112, subscript; 113, identifier:pair; 114, subscript; 115, identifier:pair; 116, identifier:longest; 117, identifier:file; 118, identifier:longest; 119, identifier:file | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 9, 21; 10, 22; 11, 23; 12, 24; 13, 25; 14, 26; 16, 27; 16, 28; 16, 29; 18, 30; 20, 31; 22, 32; 22, 33; 23, 34; 23, 35; 24, 36; 24, 37; 25, 38; 25, 39; 26, 40; 26, 41; 29, 42; 30, 43; 30, 44; 31, 45; 31, 46; 33, 47; 33, 48; 35, 49; 35, 50; 37, 51; 37, 52; 39, 53; 39, 54; 39, 55; 41, 56; 41, 57; 42, 58; 42, 59; 42, 60; 44, 61; 44, 62; 45, 63; 45, 64; 46, 65; 46, 66; 48, 67; 49, 68; 49, 69; 50, 70; 50, 71; 51, 72; 51, 73; 52, 74; 52, 75; 54, 76; 54, 77; 55, 78; 55, 79; 57, 80; 60, 81; 61, 82; 61, 83; 62, 84; 62, 85; 64, 86; 73, 87; 73, 88; 73, 89; 73, 90; 81, 91; 81, 92; 83, 93; 85, 94; 85, 95; 86, 96; 86, 97; 91, 98; 91, 99; 92, 100; 93, 101; 93, 102; 94, 103; 94, 104; 97, 105; 98, 106; 98, 107; 99, 108; 99, 109; 100, 110; 102, 111; 107, 112; 109, 113; 110, 114; 110, 115; 112, 116; 112, 117; 114, 118; 114, 119 | def fast_combine_pairs(files, force_single, full_name, separators):
"""
assume files that need to be paired are within 10 entries of each other, once the list is sorted
"""
files = sort_filenames(files)
chunks = tz.sliding_window(10, files)
pairs = [combine_pairs(chunk, force_single, full_name, separators) for chunk in chunks]
pairs = [y for x in pairs for y in x]
longest = defaultdict(list)
# for each file, save the longest pair it is in
for pair in pairs:
for file in pair:
if len(longest[file]) < len(pair):
longest[file] = pair
# keep only unique pairs
longest = {tuple(sort_filenames(x)) for x in longest.values()}
# ensure filenames are R1 followed by R2
return [sort_filenames(list(x)) for x in longest] |
0, module; 1, function_definition; 2, function_name:align_bam; 3, parameters; 4, block; 5, identifier:in_bam; 6, identifier:ref_file; 7, identifier:names; 8, identifier:align_dir; 9, identifier:data; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, comment:# adjust memory for samtools since used for input and output; 18, expression_statement; 19, if_statement; 20, return_statement; 21, comment:"""Perform direct alignment of an input BAM file with BWA using pipes.
This avoids disk IO by piping between processes:
- samtools sort of input BAM to queryname
- bedtools conversion to interleaved FASTQ
- bwa-mem alignment
- samtools conversion to BAM
- samtools sort to coordinate
"""; 22, assignment; 23, assignment; 24, assignment; 25, assignment; 26, assignment; 27, assignment; 28, assignment; 29, not_operator; 30, block; 31, identifier:out_file; 32, identifier:config; 33, subscript; 34, identifier:out_file; 35, call; 36, identifier:samtools; 37, call; 38, identifier:bedtools; 39, call; 40, identifier:resources; 41, call; 42, identifier:num_cores; 43, call; 44, identifier:max_mem; 45, call; 46, call; 47, with_statement; 48, identifier:data; 49, string:"config"; 50, attribute; 51, argument_list; 52, attribute; 53, argument_list; 54, attribute; 55, argument_list; 56, attribute; 57, argument_list; 58, attribute; 59, argument_list; 60, attribute; 61, argument_list; 62, attribute; 63, argument_list; 64, with_clause; 65, block; 66, attribute; 67, identifier:join; 68, identifier:align_dir; 69, call; 70, identifier:config_utils; 71, identifier:get_program; 72, string:"samtools"; 73, identifier:config; 74, identifier:config_utils; 75, identifier:get_program; 76, string:"bedtools"; 77, identifier:config; 78, identifier:config_utils; 79, identifier:get_resources; 80, string:"samtools"; 81, identifier:config; 82, subscript; 83, identifier:get; 84, string:"num_cores"; 85, integer:1; 86, call; 87, identifier:upper; 88, identifier:utils; 89, identifier:file_exists; 90, identifier:out_file; 91, with_item; 92, with_statement; 93, identifier:os; 94, identifier:path; 95, attribute; 96, argument_list; 97, identifier:config; 98, string:"algorithm"; 99, attribute; 100, argument_list; 101, as_pattern; 102, with_clause; 103, block; 104, string:"{0}-sort.bam"; 105, identifier:format; 106, subscript; 107, identifier:config_utils; 108, identifier:adjust_memory; 109, call; 110, integer:3; 111, string:"decrease"; 112, call; 113, as_pattern_target; 114, with_item; 115, expression_statement; 116, expression_statement; 117, expression_statement; 118, expression_statement; 119, expression_statement; 120, expression_statement; 121, identifier:names; 122, string:"lane"; 123, attribute; 124, argument_list; 125, identifier:tx_tmpdir; 126, argument_list; 127, identifier:work_dir; 128, as_pattern; 129, assignment; 130, assignment; 131, assignment; 132, assignment; 133, assignment; 134, call; 135, identifier:resources; 136, identifier:get; 137, string:"memory"; 138, string:"1G"; 139, identifier:data; 140, call; 141, as_pattern_target; 142, identifier:bwa_cmd; 143, call; 144, identifier:tx_out_prefix; 145, subscript; 146, identifier:prefix1; 147, binary_operator:"%s-in1" % tx_out_prefix; 148, identifier:cmd; 149, parenthesized_expression; 150, identifier:cmd; 151, binary_operator:cmd.format(**locals()) + tobam_cl; 152, attribute; 153, argument_list; 154, attribute; 155, argument_list; 156, tuple; 157, identifier:_get_bwa_mem_cmd; 158, argument_list; 159, call; 160, integer:0; 161, string:"%s-in1"; 162, identifier:tx_out_prefix; 163, concatenated_string; 164, call; 165, identifier:tobam_cl; 166, identifier:do; 167, identifier:run; 168, identifier:cmd; 169, binary_operator:"bwa mem alignment from BAM: %s" % names["sample"]; 170, None; 171, list; 172, identifier:postalign; 173, identifier:tobam_cl; 174, identifier:data; 175, identifier:out_file; 176, call; 177, identifier:tobam_cl; 178, identifier:tx_out_file; 179, identifier:data; 180, identifier:out_file; 181, identifier:ref_file; 182, string:"-"; 183, attribute; 184, argument_list; 185, string:"unset JAVA_HOME && "; 186, string:"{samtools} sort -n -o -l 1 -@ {num_cores} -m {max_mem} {in_bam} {prefix1} "; 187, string:"| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout "; 188, string:"| {bwa_cmd} | "; 189, attribute; 190, argument_list; 191, string:"bwa mem alignment from BAM: %s"; 192, subscript; 193, call; 194, call; 195, attribute; 196, argument_list; 197, attribute; 198, identifier:splitext; 199, identifier:tx_out_file; 200, identifier:cmd; 201, identifier:format; 202, dictionary_splat; 203, identifier:names; 204, string:"sample"; 205, attribute; 206, argument_list; 207, attribute; 208, argument_list; 209, identifier:bam; 210, identifier:is_paired; 211, identifier:in_bam; 212, identifier:os; 213, identifier:path; 214, call; 215, identifier:do; 216, identifier:file_nonempty; 217, identifier:tx_out_file; 218, identifier:do; 219, identifier:file_reasonable_size; 220, identifier:tx_out_file; 221, identifier:in_bam; 222, identifier:locals; 223, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 10, 21; 11, 22; 12, 23; 13, 24; 14, 25; 15, 26; 16, 27; 18, 28; 19, 29; 19, 30; 20, 31; 22, 32; 22, 33; 23, 34; 23, 35; 24, 36; 24, 37; 25, 38; 25, 39; 26, 40; 26, 41; 27, 42; 27, 43; 28, 44; 28, 45; 29, 46; 30, 47; 33, 48; 33, 49; 35, 50; 35, 51; 37, 52; 37, 53; 39, 54; 39, 55; 41, 56; 41, 57; 43, 58; 43, 59; 45, 60; 45, 61; 46, 62; 46, 63; 47, 64; 47, 65; 50, 66; 50, 67; 51, 68; 51, 69; 52, 70; 52, 71; 53, 72; 53, 73; 54, 74; 54, 75; 55, 76; 55, 77; 56, 78; 56, 79; 57, 80; 57, 81; 58, 82; 58, 83; 59, 84; 59, 85; 60, 86; 60, 87; 62, 88; 62, 89; 63, 90; 64, 91; 65, 92; 66, 93; 66, 94; 69, 95; 69, 96; 82, 97; 82, 98; 86, 99; 86, 100; 91, 101; 92, 102; 92, 103; 95, 104; 95, 105; 96, 106; 99, 107; 99, 108; 100, 109; 100, 110; 100, 111; 101, 112; 101, 113; 102, 114; 103, 115; 103, 116; 103, 117; 103, 118; 103, 119; 103, 120; 106, 121; 106, 122; 109, 123; 109, 124; 112, 125; 112, 126; 113, 127; 114, 128; 115, 129; 116, 130; 117, 131; 118, 132; 119, 133; 120, 134; 123, 135; 123, 136; 124, 137; 124, 138; 126, 139; 128, 140; 128, 141; 129, 142; 129, 143; 130, 144; 130, 145; 131, 146; 131, 147; 132, 148; 132, 149; 133, 150; 133, 151; 134, 152; 134, 153; 140, 154; 140, 155; 141, 156; 143, 157; 143, 158; 145, 159; 145, 160; 147, 161; 147, 162; 149, 163; 151, 164; 151, 165; 152, 166; 152, 167; 153, 168; 153, 169; 153, 170; 153, 171; 154, 172; 154, 173; 155, 174; 155, 175; 155, 176; 156, 177; 156, 178; 158, 179; 158, 180; 158, 181; 158, 182; 159, 183; 159, 184; 163, 185; 163, 186; 163, 187; 163, 188; 164, 189; 164, 190; 169, 191; 169, 192; 171, 193; 171, 194; 176, 195; 176, 196; 183, 197; 183, 198; 184, 199; 189, 200; 189, 201; 190, 202; 192, 203; 192, 204; 193, 205; 193, 206; 194, 207; 194, 208; 195, 209; 195, 210; 196, 211; 197, 212; 197, 213; 202, 214; 205, 215; 205, 216; 206, 217; 207, 218; 207, 219; 208, 220; 208, 221; 214, 222; 214, 223 | def align_bam(in_bam, ref_file, names, align_dir, data):
"""Perform direct alignment of an input BAM file with BWA using pipes.
This avoids disk IO by piping between processes:
- samtools sort of input BAM to queryname
- bedtools conversion to interleaved FASTQ
- bwa-mem alignment
- samtools conversion to BAM
- samtools sort to coordinate
"""
config = data["config"]
out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"]))
samtools = config_utils.get_program("samtools", config)
bedtools = config_utils.get_program("bedtools", config)
resources = config_utils.get_resources("samtools", config)
num_cores = config["algorithm"].get("num_cores", 1)
# adjust memory for samtools since used for input and output
max_mem = config_utils.adjust_memory(resources.get("memory", "1G"),
3, "decrease").upper()
if not utils.file_exists(out_file):
with tx_tmpdir(data) as work_dir:
with postalign.tobam_cl(data, out_file, bam.is_paired(in_bam)) as (tobam_cl, tx_out_file):
bwa_cmd = _get_bwa_mem_cmd(data, out_file, ref_file, "-")
tx_out_prefix = os.path.splitext(tx_out_file)[0]
prefix1 = "%s-in1" % tx_out_prefix
cmd = ("unset JAVA_HOME && "
"{samtools} sort -n -o -l 1 -@ {num_cores} -m {max_mem} {in_bam} {prefix1} "
"| {bedtools} bamtofastq -i /dev/stdin -fq /dev/stdout -fq2 /dev/stdout "
"| {bwa_cmd} | ")
cmd = cmd.format(**locals()) + tobam_cl
do.run(cmd, "bwa mem alignment from BAM: %s" % names["sample"], None,
[do.file_nonempty(tx_out_file), do.file_reasonable_size(tx_out_file, in_bam)])
return out_file |
0, module; 1, function_definition; 2, function_name:_combine_regions; 3, parameters; 4, block; 5, identifier:all_regions; 6, identifier:ref_regions; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, function_definition; 11, expression_statement; 12, for_statement; 13, expression_statement; 14, expression_statement; 15, return_statement; 16, comment:"""Combine multiple BEDtools regions of regions into sorted final BEDtool.
"""; 17, assignment; 18, pattern_list; 19, call; 20, block; 21, function_name:wchrom_key; 22, parameters; 23, block; 24, assignment; 25, identifier:region_group; 26, identifier:all_regions; 27, block; 28, call; 29, assignment; 30, call; 31, identifier:chrom_order; 32, dictionary; 33, identifier:i; 34, identifier:x; 35, identifier:enumerate; 36, argument_list; 37, expression_statement; 38, identifier:x; 39, expression_statement; 40, return_statement; 41, identifier:all_intervals; 42, list; 43, for_statement; 44, attribute; 45, argument_list; 46, identifier:bed_lines; 47, list_comprehension; 48, attribute; 49, argument_list; 50, identifier:ref_regions; 51, assignment; 52, assignment; 53, tuple; 54, identifier:region; 55, identifier:region_group; 56, block; 57, identifier:all_intervals; 58, identifier:sort; 59, keyword_argument; 60, binary_operator:"%s\t%s\t%s" % (c, s, e); 61, for_in_clause; 62, identifier:pybedtools; 63, identifier:BedTool; 64, call; 65, keyword_argument; 66, subscript; 67, identifier:i; 68, pattern_list; 69, identifier:x; 70, subscript; 71, identifier:start; 72, identifier:end; 73, expression_statement; 74, identifier:key; 75, identifier:wchrom_key; 76, string:"%s\t%s\t%s"; 77, tuple; 78, tuple_pattern; 79, identifier:all_intervals; 80, attribute; 81, argument_list; 82, identifier:from_string; 83, True; 84, identifier:chrom_order; 85, attribute; 86, identifier:chrom; 87, identifier:start; 88, identifier:end; 89, identifier:chrom_order; 90, identifier:chrom; 91, call; 92, identifier:c; 93, identifier:s; 94, identifier:e; 95, identifier:c; 96, identifier:s; 97, identifier:e; 98, string:"\n"; 99, identifier:join; 100, identifier:bed_lines; 101, identifier:x; 102, identifier:chrom; 103, attribute; 104, argument_list; 105, identifier:all_intervals; 106, identifier:append; 107, tuple; 108, attribute; 109, call; 110, call; 111, identifier:region; 112, identifier:chrom; 113, identifier:int; 114, argument_list; 115, identifier:int; 116, argument_list; 117, attribute; 118, attribute; 119, identifier:region; 120, identifier:start; 121, identifier:region; 122, identifier:stop | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 7, 16; 8, 17; 9, 18; 9, 19; 9, 20; 10, 21; 10, 22; 10, 23; 11, 24; 12, 25; 12, 26; 12, 27; 13, 28; 14, 29; 15, 30; 17, 31; 17, 32; 18, 33; 18, 34; 19, 35; 19, 36; 20, 37; 22, 38; 23, 39; 23, 40; 24, 41; 24, 42; 27, 43; 28, 44; 28, 45; 29, 46; 29, 47; 30, 48; 30, 49; 36, 50; 37, 51; 39, 52; 40, 53; 43, 54; 43, 55; 43, 56; 44, 57; 44, 58; 45, 59; 47, 60; 47, 61; 48, 62; 48, 63; 49, 64; 49, 65; 51, 66; 51, 67; 52, 68; 52, 69; 53, 70; 53, 71; 53, 72; 56, 73; 59, 74; 59, 75; 60, 76; 60, 77; 61, 78; 61, 79; 64, 80; 64, 81; 65, 82; 65, 83; 66, 84; 66, 85; 68, 86; 68, 87; 68, 88; 70, 89; 70, 90; 73, 91; 77, 92; 77, 93; 77, 94; 78, 95; 78, 96; 78, 97; 80, 98; 80, 99; 81, 100; 85, 101; 85, 102; 91, 103; 91, 104; 103, 105; 103, 106; 104, 107; 107, 108; 107, 109; 107, 110; 108, 111; 108, 112; 109, 113; 109, 114; 110, 115; 110, 116; 114, 117; 116, 118; 117, 119; 117, 120; 118, 121; 118, 122 | def _combine_regions(all_regions, ref_regions):
"""Combine multiple BEDtools regions of regions into sorted final BEDtool.
"""
chrom_order = {}
for i, x in enumerate(ref_regions):
chrom_order[x.chrom] = i
def wchrom_key(x):
chrom, start, end = x
return (chrom_order[chrom], start, end)
all_intervals = []
for region_group in all_regions:
for region in region_group:
all_intervals.append((region.chrom, int(region.start), int(region.stop)))
all_intervals.sort(key=wchrom_key)
bed_lines = ["%s\t%s\t%s" % (c, s, e) for (c, s, e) in all_intervals]
return pybedtools.BedTool("\n".join(bed_lines), from_string=True) |
0, module; 1, function_definition; 2, function_name:_add_meta; 3, parameters; 4, block; 5, identifier:xs; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, for_statement; 11, return_statement; 12, identifier:sample; 13, None; 14, identifier:config; 15, None; 16, comment:"""Add top level information about the sample or flowcell to output.
Sorts outputs into sample names (sample input) and project (config input).
"""; 17, assignment; 18, identifier:x; 19, identifier:xs; 20, block; 21, identifier:out; 22, identifier:out; 23, list; 24, if_statement; 25, expression_statement; 26, if_statement; 27, if_statement; 28, expression_statement; 29, boolean_operator; 30, block; 31, assignment; 32, identifier:sample; 33, block; 34, identifier:config; 35, block; 36, call; 37, not_operator; 38, not_operator; 39, raise_statement; 40, subscript; 41, call; 42, expression_statement; 43, if_statement; 44, expression_statement; 45, expression_statement; 46, expression_statement; 47, attribute; 48, argument_list; 49, call; 50, call; 51, call; 52, identifier:x; 53, string:"mtime"; 54, attribute; 55, argument_list; 56, assignment; 57, comparison_operator:"sample" not in x; 58, block; 59, elif_clause; 60, assignment; 61, assignment; 62, assignment; 63, identifier:out; 64, identifier:append; 65, identifier:x; 66, identifier:isinstance; 67, argument_list; 68, attribute; 69, argument_list; 70, identifier:ValueError; 71, argument_list; 72, identifier:shared; 73, identifier:get_file_timestamp; 74, subscript; 75, identifier:sample_name; 76, call; 77, string:"sample"; 78, identifier:x; 79, expression_statement; 80, comparison_operator:x["sample"] != sample_name; 81, block; 82, identifier:fc_name; 83, boolean_operator; 84, identifier:fc_date; 85, boolean_operator; 86, subscript; 87, binary_operator:"%s_%s" % (fc_date, fc_name); 88, subscript; 89, attribute; 90, attribute; 91, identifier:exists; 92, subscript; 93, binary_operator:"Unexpected path for upload: %s" % x; 94, identifier:x; 95, string:"path"; 96, attribute; 97, argument_list; 98, assignment; 99, subscript; 100, identifier:sample_name; 101, expression_statement; 102, call; 103, string:"project"; 104, call; 105, call; 106, identifier:x; 107, string:"run"; 108, string:"%s_%s"; 109, tuple; 110, identifier:x; 111, string:"path"; 112, identifier:six; 113, identifier:string_types; 114, identifier:os; 115, identifier:path; 116, identifier:x; 117, string:"path"; 118, string:"Unexpected path for upload: %s"; 119, identifier:x; 120, identifier:dd; 121, identifier:get_sample_name; 122, identifier:sample; 123, subscript; 124, identifier:sample_name; 125, identifier:x; 126, string:"sample"; 127, assignment; 128, attribute; 129, argument_list; 130, attribute; 131, argument_list; 132, attribute; 133, argument_list; 134, identifier:fc_date; 135, identifier:fc_name; 136, identifier:x; 137, string:"sample"; 138, subscript; 139, identifier:sample_name; 140, identifier:config; 141, identifier:get; 142, string:"fc_name"; 143, identifier:config; 144, identifier:get; 145, string:"fc_date"; 146, call; 147, identifier:strftime; 148, string:"%Y-%m-%d"; 149, identifier:x; 150, string:"run"; 151, attribute; 152, argument_list; 153, attribute; 154, identifier:now; 155, identifier:datetime; 156, identifier:datetime | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 7, 15; 8, 16; 9, 17; 10, 18; 10, 19; 10, 20; 11, 21; 17, 22; 17, 23; 20, 24; 20, 25; 20, 26; 20, 27; 20, 28; 24, 29; 24, 30; 25, 31; 26, 32; 26, 33; 27, 34; 27, 35; 28, 36; 29, 37; 29, 38; 30, 39; 31, 40; 31, 41; 33, 42; 33, 43; 35, 44; 35, 45; 35, 46; 36, 47; 36, 48; 37, 49; 38, 50; 39, 51; 40, 52; 40, 53; 41, 54; 41, 55; 42, 56; 43, 57; 43, 58; 43, 59; 44, 60; 45, 61; 46, 62; 47, 63; 47, 64; 48, 65; 49, 66; 49, 67; 50, 68; 50, 69; 51, 70; 51, 71; 54, 72; 54, 73; 55, 74; 56, 75; 56, 76; 57, 77; 57, 78; 58, 79; 59, 80; 59, 81; 60, 82; 60, 83; 61, 84; 61, 85; 62, 86; 62, 87; 67, 88; 67, 89; 68, 90; 68, 91; 69, 92; 71, 93; 74, 94; 74, 95; 76, 96; 76, 97; 79, 98; 80, 99; 80, 100; 81, 101; 83, 102; 83, 103; 85, 104; 85, 105; 86, 106; 86, 107; 87, 108; 87, 109; 88, 110; 88, 111; 89, 112; 89, 113; 90, 114; 90, 115; 92, 116; 92, 117; 93, 118; 93, 119; 96, 120; 96, 121; 97, 122; 98, 123; 98, 124; 99, 125; 99, 126; 101, 127; 102, 128; 102, 129; 104, 130; 104, 131; 105, 132; 105, 133; 109, 134; 109, 135; 123, 136; 123, 137; 127, 138; 127, 139; 128, 140; 128, 141; 129, 142; 130, 143; 130, 144; 131, 145; 132, 146; 132, 147; 133, 148; 138, 149; 138, 150; 146, 151; 146, 152; 151, 153; 151, 154; 153, 155; 153, 156 | def _add_meta(xs, sample=None, config=None):
"""Add top level information about the sample or flowcell to output.
Sorts outputs into sample names (sample input) and project (config input).
"""
out = []
for x in xs:
if not isinstance(x["path"], six.string_types) or not os.path.exists(x["path"]):
raise ValueError("Unexpected path for upload: %s" % x)
x["mtime"] = shared.get_file_timestamp(x["path"])
if sample:
sample_name = dd.get_sample_name(sample)
if "sample" not in x:
x["sample"] = sample_name
elif x["sample"] != sample_name:
x["run"] = sample_name
if config:
fc_name = config.get("fc_name") or "project"
fc_date = config.get("fc_date") or datetime.datetime.now().strftime("%Y-%m-%d")
x["run"] = "%s_%s" % (fc_date, fc_name)
out.append(x)
return out |
0, module; 1, function_definition; 2, function_name:report; 3, parameters; 4, block; 5, identifier:self; 6, identifier:align_bam; 7, identifier:ref_file; 8, identifier:is_paired; 9, identifier:bait_file; 10, identifier:target_file; 11, identifier:variant_region_file; 12, identifier:config; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, comment:# Prefer the GC metrics in FastQC instead of Picard; 17, comment:# gc_graph, gc_metrics = self._gc_bias(align_bam, ref_file); 18, expression_statement; 19, expression_statement; 20, if_statement; 21, if_statement; 22, expression_statement; 23, expression_statement; 24, expression_statement; 25, if_statement; 26, if_statement; 27, return_statement; 28, comment:"""Produce report metrics using Picard with sorted aligned BAM file.
"""; 29, assignment; 30, assignment; 31, assignment; 32, assignment; 33, identifier:is_paired; 34, block; 35, boolean_operator; 36, block; 37, elif_clause; 38, assignment; 39, assignment; 40, assignment; 41, boolean_operator; 42, block; 43, boolean_operator; 44, block; 45, expression_list; 46, identifier:dup_metrics; 47, call; 48, identifier:align_metrics; 49, call; 50, identifier:gc_graph; 51, None; 52, pattern_list; 53, tuple; 54, expression_statement; 55, identifier:bait_file; 56, identifier:target_file; 57, assert_statement; 58, assert_statement; 59, expression_statement; 60, parenthesized_expression; 61, block; 62, identifier:vrn_vals; 63, call; 64, identifier:summary_info; 65, call; 66, identifier:graphs; 67, list; 68, identifier:gc_graph; 69, call; 70, expression_statement; 71, identifier:insert_graph; 72, call; 73, expression_statement; 74, identifier:summary_info; 75, identifier:graphs; 76, attribute; 77, argument_list; 78, attribute; 79, argument_list; 80, identifier:insert_graph; 81, identifier:insert_metrics; 82, identifier:hybrid_metrics; 83, None; 84, None; 85, None; 86, assignment; 87, call; 88, tuple; 89, call; 90, tuple; 91, assignment; 92, boolean_operator; 93, assert_statement; 94, expression_statement; 95, attribute; 96, argument_list; 97, attribute; 98, argument_list; 99, attribute; 100, argument_list; 101, call; 102, attribute; 103, argument_list; 104, call; 105, identifier:self; 106, identifier:_get_current_dup_metrics; 107, identifier:align_bam; 108, identifier:self; 109, identifier:_collect_align_metrics; 110, identifier:align_bam; 111, identifier:ref_file; 112, pattern_list; 113, call; 114, attribute; 115, argument_list; 116, identifier:bait_file; 117, string:"does not exist!"; 118, attribute; 119, argument_list; 120, identifier:target_file; 121, string:"does not exist!"; 122, identifier:hybrid_metrics; 123, call; 124, identifier:variant_region_file; 125, comparison_operator:config["algorithm"].get("coverage_interval", "").lower() in ["exome"]; 126, call; 127, tuple; 128, assignment; 129, identifier:self; 130, identifier:_variant_eval_metrics; 131, identifier:align_bam; 132, attribute; 133, identifier:get_summary_metrics; 134, identifier:align_metrics; 135, identifier:dup_metrics; 136, identifier:insert_metrics; 137, identifier:hybrid_metrics; 138, identifier:vrn_vals; 139, attribute; 140, identifier:exists; 141, identifier:gc_graph; 142, attribute; 143, argument_list; 144, attribute; 145, identifier:exists; 146, identifier:insert_graph; 147, attribute; 148, argument_list; 149, identifier:insert_graph; 150, identifier:insert_metrics; 151, attribute; 152, argument_list; 153, attribute; 154, identifier:exists; 155, identifier:bait_file; 156, attribute; 157, identifier:exists; 158, identifier:target_file; 159, attribute; 160, argument_list; 161, call; 162, list; 163, attribute; 164, argument_list; 165, identifier:variant_region_file; 166, string:"does not exist"; 167, identifier:hybrid_metrics; 168, call; 169, identifier:self; 170, identifier:_parser; 171, identifier:os; 172, identifier:path; 173, identifier:graphs; 174, identifier:append; 175, tuple; 176, identifier:os; 177, identifier:path; 178, identifier:graphs; 179, identifier:append; 180, tuple; 181, identifier:self; 182, identifier:_insert_sizes; 183, identifier:align_bam; 184, identifier:os; 185, identifier:path; 186, identifier:os; 187, identifier:path; 188, identifier:self; 189, identifier:_hybrid_select_metrics; 190, identifier:align_bam; 191, identifier:bait_file; 192, identifier:target_file; 193, attribute; 194, argument_list; 195, string:"exome"; 196, attribute; 197, identifier:exists; 198, identifier:variant_region_file; 199, attribute; 200, argument_list; 201, identifier:gc_graph; 202, string:"Distribution of GC content across reads"; 203, identifier:insert_graph; 204, string:"Distribution of paired end insert sizes"; 205, call; 206, identifier:lower; 207, identifier:os; 208, identifier:path; 209, identifier:self; 210, identifier:_hybrid_select_metrics; 211, identifier:align_bam; 212, identifier:variant_region_file; 213, identifier:variant_region_file; 214, attribute; 215, argument_list; 216, subscript; 217, identifier:get; 218, string:"coverage_interval"; 219, string:""; 220, identifier:config; 221, string:"algorithm" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 13, 28; 14, 29; 15, 30; 18, 31; 19, 32; 20, 33; 20, 34; 21, 35; 21, 36; 21, 37; 22, 38; 23, 39; 24, 40; 25, 41; 25, 42; 26, 43; 26, 44; 27, 45; 29, 46; 29, 47; 30, 48; 30, 49; 31, 50; 31, 51; 32, 52; 32, 53; 34, 54; 35, 55; 35, 56; 36, 57; 36, 58; 36, 59; 37, 60; 37, 61; 38, 62; 38, 63; 39, 64; 39, 65; 40, 66; 40, 67; 41, 68; 41, 69; 42, 70; 43, 71; 43, 72; 44, 73; 45, 74; 45, 75; 47, 76; 47, 77; 49, 78; 49, 79; 52, 80; 52, 81; 52, 82; 53, 83; 53, 84; 53, 85; 54, 86; 57, 87; 57, 88; 58, 89; 58, 90; 59, 91; 60, 92; 61, 93; 61, 94; 63, 95; 63, 96; 65, 97; 65, 98; 69, 99; 69, 100; 70, 101; 72, 102; 72, 103; 73, 104; 76, 105; 76, 106; 77, 107; 78, 108; 78, 109; 79, 110; 79, 111; 86, 112; 86, 113; 87, 114; 87, 115; 88, 116; 88, 117; 89, 118; 89, 119; 90, 120; 90, 121; 91, 122; 91, 123; 92, 124; 92, 125; 93, 126; 93, 127; 94, 128; 95, 129; 95, 130; 96, 131; 97, 132; 97, 133; 98, 134; 98, 135; 98, 136; 98, 137; 98, 138; 99, 139; 99, 140; 100, 141; 101, 142; 101, 143; 102, 144; 102, 145; 103, 146; 104, 147; 104, 148; 112, 149; 112, 150; 113, 151; 113, 152; 114, 153; 114, 154; 115, 155; 118, 156; 118, 157; 119, 158; 123, 159; 123, 160; 125, 161; 125, 162; 126, 163; 126, 164; 127, 165; 127, 166; 128, 167; 128, 168; 132, 169; 132, 170; 139, 171; 139, 172; 142, 173; 142, 174; 143, 175; 144, 176; 144, 177; 147, 178; 147, 179; 148, 180; 151, 181; 151, 182; 152, 183; 153, 184; 153, 185; 156, 186; 156, 187; 159, 188; 159, 189; 160, 190; 160, 191; 160, 192; 161, 193; 161, 194; 162, 195; 163, 196; 163, 197; 164, 198; 168, 199; 168, 200; 175, 201; 175, 202; 180, 203; 180, 204; 193, 205; 193, 206; 196, 207; 196, 208; 199, 209; 199, 210; 200, 211; 200, 212; 200, 213; 205, 214; 205, 215; 214, 216; 214, 217; 215, 218; 215, 219; 216, 220; 216, 221 | def report(self, align_bam, ref_file, is_paired, bait_file, target_file,
variant_region_file, config):
"""Produce report metrics using Picard with sorted aligned BAM file.
"""
dup_metrics = self._get_current_dup_metrics(align_bam)
align_metrics = self._collect_align_metrics(align_bam, ref_file)
# Prefer the GC metrics in FastQC instead of Picard
# gc_graph, gc_metrics = self._gc_bias(align_bam, ref_file)
gc_graph = None
insert_graph, insert_metrics, hybrid_metrics = (None, None, None)
if is_paired:
insert_graph, insert_metrics = self._insert_sizes(align_bam)
if bait_file and target_file:
assert os.path.exists(bait_file), (bait_file, "does not exist!")
assert os.path.exists(target_file), (target_file, "does not exist!")
hybrid_metrics = self._hybrid_select_metrics(align_bam,
bait_file, target_file)
elif (variant_region_file and
config["algorithm"].get("coverage_interval", "").lower() in ["exome"]):
assert os.path.exists(variant_region_file), (variant_region_file, "does not exist")
hybrid_metrics = self._hybrid_select_metrics(
align_bam, variant_region_file, variant_region_file)
vrn_vals = self._variant_eval_metrics(align_bam)
summary_info = self._parser.get_summary_metrics(align_metrics,
dup_metrics, insert_metrics, hybrid_metrics,
vrn_vals)
graphs = []
if gc_graph and os.path.exists(gc_graph):
graphs.append((gc_graph, "Distribution of GC content across reads"))
if insert_graph and os.path.exists(insert_graph):
graphs.append((insert_graph, "Distribution of paired end insert sizes"))
return summary_info, graphs |
0, module; 1, function_definition; 2, function_name:report; 3, parameters; 4, block; 5, identifier:self; 6, identifier:align_bam; 7, identifier:ref_file; 8, identifier:gtf_file; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, comment:# collect duplication metrics; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, if_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, if_statement; 21, return_statement; 22, identifier:is_paired; 23, False; 24, identifier:rrna_file; 25, string:"null"; 26, comment:"""Produce report metrics for a RNASeq experiment using Picard
with a sorted aligned BAM file.
"""; 27, assignment; 28, assignment; 29, assignment; 30, identifier:is_paired; 31, block; 32, assignment; 33, assignment; 34, assignment; 35, boolean_operator; 36, block; 37, expression_list; 38, identifier:dup_metrics; 39, call; 40, identifier:align_metrics; 41, call; 42, pattern_list; 43, tuple; 44, expression_statement; 45, identifier:rnaseq_metrics; 46, call; 47, identifier:summary_info; 48, call; 49, identifier:graphs; 50, list; 51, identifier:insert_graph; 52, call; 53, expression_statement; 54, identifier:summary_info; 55, identifier:graphs; 56, attribute; 57, argument_list; 58, attribute; 59, argument_list; 60, identifier:insert_graph; 61, identifier:insert_metrics; 62, None; 63, None; 64, assignment; 65, attribute; 66, argument_list; 67, attribute; 68, argument_list; 69, identifier:file_exists; 70, argument_list; 71, call; 72, identifier:self; 73, identifier:_get_current_dup_metrics; 74, identifier:align_bam; 75, identifier:self; 76, identifier:_collect_align_metrics; 77, identifier:align_bam; 78, identifier:ref_file; 79, pattern_list; 80, call; 81, identifier:self; 82, identifier:_rnaseq_metrics; 83, identifier:align_bam; 84, identifier:gtf_file; 85, identifier:rrna_file; 86, attribute; 87, identifier:get_summary_metrics; 88, identifier:align_metrics; 89, identifier:dup_metrics; 90, keyword_argument; 91, keyword_argument; 92, identifier:insert_graph; 93, attribute; 94, argument_list; 95, identifier:insert_graph; 96, identifier:insert_metrics; 97, attribute; 98, argument_list; 99, identifier:self; 100, identifier:_parser; 101, identifier:insert_metrics; 102, identifier:insert_metrics; 103, identifier:rnaseq_metrics; 104, identifier:rnaseq_metrics; 105, identifier:graphs; 106, identifier:append; 107, tuple; 108, identifier:self; 109, identifier:_insert_sizes; 110, identifier:align_bam; 111, identifier:insert_graph; 112, string:"Distribution of paired end insert sizes" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 9, 22; 9, 23; 10, 24; 10, 25; 11, 26; 13, 27; 14, 28; 15, 29; 16, 30; 16, 31; 17, 32; 18, 33; 19, 34; 20, 35; 20, 36; 21, 37; 27, 38; 27, 39; 28, 40; 28, 41; 29, 42; 29, 43; 31, 44; 32, 45; 32, 46; 33, 47; 33, 48; 34, 49; 34, 50; 35, 51; 35, 52; 36, 53; 37, 54; 37, 55; 39, 56; 39, 57; 41, 58; 41, 59; 42, 60; 42, 61; 43, 62; 43, 63; 44, 64; 46, 65; 46, 66; 48, 67; 48, 68; 52, 69; 52, 70; 53, 71; 56, 72; 56, 73; 57, 74; 58, 75; 58, 76; 59, 77; 59, 78; 64, 79; 64, 80; 65, 81; 65, 82; 66, 83; 66, 84; 66, 85; 67, 86; 67, 87; 68, 88; 68, 89; 68, 90; 68, 91; 70, 92; 71, 93; 71, 94; 79, 95; 79, 96; 80, 97; 80, 98; 86, 99; 86, 100; 90, 101; 90, 102; 91, 103; 91, 104; 93, 105; 93, 106; 94, 107; 97, 108; 97, 109; 98, 110; 107, 111; 107, 112 | def report(self, align_bam, ref_file, gtf_file, is_paired=False, rrna_file="null"):
"""Produce report metrics for a RNASeq experiment using Picard
with a sorted aligned BAM file.
"""
# collect duplication metrics
dup_metrics = self._get_current_dup_metrics(align_bam)
align_metrics = self._collect_align_metrics(align_bam, ref_file)
insert_graph, insert_metrics = (None, None)
if is_paired:
insert_graph, insert_metrics = self._insert_sizes(align_bam)
rnaseq_metrics = self._rnaseq_metrics(align_bam, gtf_file, rrna_file)
summary_info = self._parser.get_summary_metrics(align_metrics,
dup_metrics,
insert_metrics=insert_metrics,
rnaseq_metrics=rnaseq_metrics)
graphs = []
if insert_graph and file_exists(insert_graph):
graphs.append((insert_graph,
"Distribution of paired end insert sizes"))
return summary_info, graphs |
0, module; 1, function_definition; 2, function_name:apply_recal; 3, parameters; 4, block; 5, identifier:data; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, comment:# CWL does not have work/alignment BAM separation; 11, if_statement; 12, if_statement; 13, return_statement; 14, comment:"""Apply recalibration tables to the sorted aligned BAM, producing recalibrated BAM.
"""; 15, assignment; 16, assignment; 17, comparison_operator:dd.get_recalibrate(data) in [True, "gatk"]; 18, block; 19, elif_clause; 20, elif_clause; 21, boolean_operator; 22, block; 23, boolean_operator; 24, block; 25, identifier:data; 26, identifier:orig_bam; 27, boolean_operator; 28, identifier:had_work_bam; 29, comparison_operator:"work_bam" in data; 30, call; 31, list; 32, if_statement; 33, comparison_operator:dd.get_recalibrate(data) == "sentieon"; 34, block; 35, call; 36, block; 37, not_operator; 38, call; 39, expression_statement; 40, comparison_operator:orig_bam != dd.get_work_bam(data); 41, comparison_operator:orig_bam != dd.get_align_bam(data); 42, expression_statement; 43, call; 44, call; 45, string:"work_bam"; 46, identifier:data; 47, attribute; 48, argument_list; 49, True; 50, string:"gatk"; 51, call; 52, block; 53, call; 54, string:"sentieon"; 55, if_statement; 56, attribute; 57, argument_list; 58, raise_statement; 59, identifier:had_work_bam; 60, attribute; 61, argument_list; 62, assignment; 63, identifier:orig_bam; 64, call; 65, identifier:orig_bam; 66, call; 67, call; 68, attribute; 69, argument_list; 70, attribute; 71, argument_list; 72, identifier:dd; 73, identifier:get_recalibrate; 74, identifier:data; 75, attribute; 76, argument_list; 77, expression_statement; 78, expression_statement; 79, attribute; 80, argument_list; 81, call; 82, block; 83, identifier:dd; 84, identifier:get_recalibrate; 85, identifier:data; 86, call; 87, identifier:dd; 88, identifier:get_work_bam; 89, identifier:data; 90, subscript; 91, call; 92, attribute; 93, argument_list; 94, attribute; 95, argument_list; 96, attribute; 97, argument_list; 98, identifier:dd; 99, identifier:get_align_bam; 100, identifier:data; 101, identifier:dd; 102, identifier:get_work_bam; 103, identifier:data; 104, identifier:data; 105, identifier:get; 106, string:"prep_recal"; 107, call; 108, assignment; 109, identifier:dd; 110, identifier:get_recalibrate; 111, identifier:data; 112, attribute; 113, argument_list; 114, expression_statement; 115, expression_statement; 116, identifier:NotImplementedError; 117, argument_list; 118, identifier:data; 119, string:"align_bam"; 120, attribute; 121, argument_list; 122, identifier:dd; 123, identifier:get_work_bam; 124, identifier:data; 125, identifier:dd; 126, identifier:get_align_bam; 127, identifier:data; 128, identifier:utils; 129, identifier:save_diskspace; 130, identifier:orig_bam; 131, binary_operator:"BAM recalibrated to %s" % dd.get_work_bam(data); 132, subscript; 133, attribute; 134, argument_list; 135, subscript; 136, call; 137, identifier:data; 138, identifier:get; 139, string:"prep_recal"; 140, call; 141, assignment; 142, binary_operator:"Unsupported recalibration type: %s" % (dd.get_recalibrate(data)); 143, identifier:dd; 144, identifier:get_work_bam; 145, identifier:data; 146, string:"BAM recalibrated to %s"; 147, call; 148, identifier:data; 149, string:"config"; 150, identifier:logger; 151, identifier:info; 152, binary_operator:"Applying BQSR recalibration with GATK: %s " % str(dd.get_sample_name(data)); 153, identifier:data; 154, string:"work_bam"; 155, identifier:_gatk_apply_bqsr; 156, argument_list; 157, attribute; 158, argument_list; 159, subscript; 160, call; 161, string:"Unsupported recalibration type: %s"; 162, parenthesized_expression; 163, attribute; 164, argument_list; 165, string:"Applying BQSR recalibration with GATK: %s "; 166, call; 167, identifier:data; 168, identifier:logger; 169, identifier:info; 170, binary_operator:"Applying BQSR recalibration with sentieon: %s " % str(dd.get_sample_name(data)); 171, identifier:data; 172, string:"work_bam"; 173, attribute; 174, argument_list; 175, call; 176, identifier:dd; 177, identifier:get_work_bam; 178, identifier:data; 179, identifier:str; 180, argument_list; 181, string:"Applying BQSR recalibration with sentieon: %s "; 182, call; 183, identifier:sentieon; 184, identifier:apply_bqsr; 185, identifier:data; 186, attribute; 187, argument_list; 188, call; 189, identifier:str; 190, argument_list; 191, identifier:dd; 192, identifier:get_recalibrate; 193, identifier:data; 194, attribute; 195, argument_list; 196, call; 197, identifier:dd; 198, identifier:get_sample_name; 199, identifier:data; 200, attribute; 201, argument_list; 202, identifier:dd; 203, identifier:get_sample_name; 204, identifier:data | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 7, 15; 8, 16; 9, 17; 9, 18; 9, 19; 9, 20; 11, 21; 11, 22; 12, 23; 12, 24; 13, 25; 15, 26; 15, 27; 16, 28; 16, 29; 17, 30; 17, 31; 18, 32; 19, 33; 19, 34; 20, 35; 20, 36; 21, 37; 21, 38; 22, 39; 23, 40; 23, 41; 24, 42; 27, 43; 27, 44; 29, 45; 29, 46; 30, 47; 30, 48; 31, 49; 31, 50; 32, 51; 32, 52; 33, 53; 33, 54; 34, 55; 35, 56; 35, 57; 36, 58; 37, 59; 38, 60; 38, 61; 39, 62; 40, 63; 40, 64; 41, 65; 41, 66; 42, 67; 43, 68; 43, 69; 44, 70; 44, 71; 47, 72; 47, 73; 48, 74; 51, 75; 51, 76; 52, 77; 52, 78; 53, 79; 53, 80; 55, 81; 55, 82; 56, 83; 56, 84; 57, 85; 58, 86; 60, 87; 60, 88; 61, 89; 62, 90; 62, 91; 64, 92; 64, 93; 66, 94; 66, 95; 67, 96; 67, 97; 68, 98; 68, 99; 69, 100; 70, 101; 70, 102; 71, 103; 75, 104; 75, 105; 76, 106; 77, 107; 78, 108; 79, 109; 79, 110; 80, 111; 81, 112; 81, 113; 82, 114; 82, 115; 86, 116; 86, 117; 90, 118; 90, 119; 91, 120; 91, 121; 92, 122; 92, 123; 93, 124; 94, 125; 94, 126; 95, 127; 96, 128; 96, 129; 97, 130; 97, 131; 97, 132; 107, 133; 107, 134; 108, 135; 108, 136; 112, 137; 112, 138; 113, 139; 114, 140; 115, 141; 117, 142; 120, 143; 120, 144; 121, 145; 131, 146; 131, 147; 132, 148; 132, 149; 133, 150; 133, 151; 134, 152; 135, 153; 135, 154; 136, 155; 136, 156; 140, 157; 140, 158; 141, 159; 141, 160; 142, 161; 142, 162; 147, 163; 147, 164; 152, 165; 152, 166; 156, 167; 157, 168; 157, 169; 158, 170; 159, 171; 159, 172; 160, 173; 160, 174; 162, 175; 163, 176; 163, 177; 164, 178; 166, 179; 166, 180; 170, 181; 170, 182; 173, 183; 173, 184; 174, 185; 175, 186; 175, 187; 180, 188; 182, 189; 182, 190; 186, 191; 186, 192; 187, 193; 188, 194; 188, 195; 190, 196; 194, 197; 194, 198; 195, 199; 196, 200; 196, 201; 200, 202; 200, 203; 201, 204 | def apply_recal(data):
"""Apply recalibration tables to the sorted aligned BAM, producing recalibrated BAM.
"""
orig_bam = dd.get_align_bam(data) or dd.get_work_bam(data)
had_work_bam = "work_bam" in data
if dd.get_recalibrate(data) in [True, "gatk"]:
if data.get("prep_recal"):
logger.info("Applying BQSR recalibration with GATK: %s " % str(dd.get_sample_name(data)))
data["work_bam"] = _gatk_apply_bqsr(data)
elif dd.get_recalibrate(data) == "sentieon":
if data.get("prep_recal"):
logger.info("Applying BQSR recalibration with sentieon: %s " % str(dd.get_sample_name(data)))
data["work_bam"] = sentieon.apply_bqsr(data)
elif dd.get_recalibrate(data):
raise NotImplementedError("Unsupported recalibration type: %s" % (dd.get_recalibrate(data)))
# CWL does not have work/alignment BAM separation
if not had_work_bam and dd.get_work_bam(data):
data["align_bam"] = dd.get_work_bam(data)
if orig_bam != dd.get_work_bam(data) and orig_bam != dd.get_align_bam(data):
utils.save_diskspace(orig_bam, "BAM recalibrated to %s" % dd.get_work_bam(data), data["config"])
return data |
0, module; 1, function_definition; 2, function_name:_prep_callable_bed; 3, parameters; 4, block; 5, identifier:in_file; 6, identifier:work_dir; 7, identifier:stats; 8, identifier:data; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, if_statement; 13, return_statement; 14, comment:"""Sort and merge callable BED regions to prevent SV double counting
"""; 15, assignment; 16, assignment; 17, not_operator; 18, block; 19, call; 20, identifier:out_file; 21, call; 22, identifier:gsort; 23, call; 24, call; 25, with_statement; 26, attribute; 27, argument_list; 28, attribute; 29, argument_list; 30, attribute; 31, argument_list; 32, attribute; 33, argument_list; 34, with_clause; 35, block; 36, identifier:vcfutils; 37, identifier:bgzip_and_index; 38, identifier:out_file; 39, subscript; 40, attribute; 41, identifier:join; 42, identifier:work_dir; 43, binary_operator:"%s-merge.bed.gz" % utils.splitext_plus(os.path.basename(in_file))[0]; 44, identifier:config_utils; 45, identifier:get_program; 46, string:"gsort"; 47, identifier:data; 48, identifier:utils; 49, identifier:file_uptodate; 50, identifier:out_file; 51, identifier:in_file; 52, with_item; 53, expression_statement; 54, expression_statement; 55, expression_statement; 56, identifier:data; 57, string:"config"; 58, identifier:os; 59, identifier:path; 60, string:"%s-merge.bed.gz"; 61, subscript; 62, as_pattern; 63, assignment; 64, assignment; 65, call; 66, call; 67, integer:0; 68, call; 69, as_pattern_target; 70, identifier:fai_file; 71, call; 72, identifier:cmd; 73, parenthesized_expression; 74, attribute; 75, argument_list; 76, attribute; 77, argument_list; 78, identifier:file_transaction; 79, argument_list; 80, identifier:tx_out_file; 81, attribute; 82, argument_list; 83, concatenated_string; 84, identifier:do; 85, identifier:run; 86, call; 87, string:"Prepare SV callable BED regions"; 88, identifier:utils; 89, identifier:splitext_plus; 90, call; 91, identifier:data; 92, identifier:out_file; 93, identifier:ref; 94, identifier:fasta_idx; 95, call; 96, string:"{gsort} {in_file} {fai_file} | bedtools merge -i - -d {stats[merge_size]} | "; 97, string:"bgzip -c > {tx_out_file}"; 98, attribute; 99, argument_list; 100, attribute; 101, argument_list; 102, attribute; 103, argument_list; 104, identifier:cmd; 105, identifier:format; 106, dictionary_splat; 107, attribute; 108, identifier:basename; 109, identifier:in_file; 110, identifier:dd; 111, identifier:get_ref_file; 112, identifier:data; 113, call; 114, identifier:os; 115, identifier:path; 116, identifier:locals; 117, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 9, 14; 10, 15; 11, 16; 12, 17; 12, 18; 13, 19; 15, 20; 15, 21; 16, 22; 16, 23; 17, 24; 18, 25; 19, 26; 19, 27; 21, 28; 21, 29; 23, 30; 23, 31; 24, 32; 24, 33; 25, 34; 25, 35; 26, 36; 26, 37; 27, 38; 27, 39; 28, 40; 28, 41; 29, 42; 29, 43; 30, 44; 30, 45; 31, 46; 31, 47; 32, 48; 32, 49; 33, 50; 33, 51; 34, 52; 35, 53; 35, 54; 35, 55; 39, 56; 39, 57; 40, 58; 40, 59; 43, 60; 43, 61; 52, 62; 53, 63; 54, 64; 55, 65; 61, 66; 61, 67; 62, 68; 62, 69; 63, 70; 63, 71; 64, 72; 64, 73; 65, 74; 65, 75; 66, 76; 66, 77; 68, 78; 68, 79; 69, 80; 71, 81; 71, 82; 73, 83; 74, 84; 74, 85; 75, 86; 75, 87; 76, 88; 76, 89; 77, 90; 79, 91; 79, 92; 81, 93; 81, 94; 82, 95; 83, 96; 83, 97; 86, 98; 86, 99; 90, 100; 90, 101; 95, 102; 95, 103; 98, 104; 98, 105; 99, 106; 100, 107; 100, 108; 101, 109; 102, 110; 102, 111; 103, 112; 106, 113; 107, 114; 107, 115; 113, 116; 113, 117 | def _prep_callable_bed(in_file, work_dir, stats, data):
"""Sort and merge callable BED regions to prevent SV double counting
"""
out_file = os.path.join(work_dir, "%s-merge.bed.gz" % utils.splitext_plus(os.path.basename(in_file))[0])
gsort = config_utils.get_program("gsort", data)
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
fai_file = ref.fasta_idx(dd.get_ref_file(data))
cmd = ("{gsort} {in_file} {fai_file} | bedtools merge -i - -d {stats[merge_size]} | "
"bgzip -c > {tx_out_file}")
do.run(cmd.format(**locals()), "Prepare SV callable BED regions")
return vcfutils.bgzip_and_index(out_file, data["config"]) |
0, module; 1, function_definition; 2, function_name:fake_index; 3, parameters; 4, block; 5, identifier:in_bam; 6, identifier:data; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, return_statement; 11, comment:"""Create a fake index file for namesorted BAMs. bais require by CWL for consistency.
"""; 12, assignment; 13, not_operator; 14, block; 15, identifier:index_file; 16, identifier:index_file; 17, binary_operator:"%s.bai" % in_bam; 18, call; 19, with_statement; 20, string:"%s.bai"; 21, identifier:in_bam; 22, attribute; 23, argument_list; 24, with_clause; 25, block; 26, identifier:utils; 27, identifier:file_exists; 28, identifier:index_file; 29, with_item; 30, with_statement; 31, as_pattern; 32, with_clause; 33, block; 34, call; 35, as_pattern_target; 36, with_item; 37, expression_statement; 38, identifier:file_transaction; 39, argument_list; 40, identifier:tx_out_file; 41, as_pattern; 42, call; 43, identifier:data; 44, identifier:index_file; 45, call; 46, as_pattern_target; 47, attribute; 48, argument_list; 49, identifier:open; 50, argument_list; 51, identifier:out_handle; 52, identifier:out_handle; 53, identifier:write; 54, string:"name sorted -- no index"; 55, identifier:tx_out_file; 56, string:"w" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 9, 14; 10, 15; 12, 16; 12, 17; 13, 18; 14, 19; 17, 20; 17, 21; 18, 22; 18, 23; 19, 24; 19, 25; 22, 26; 22, 27; 23, 28; 24, 29; 25, 30; 29, 31; 30, 32; 30, 33; 31, 34; 31, 35; 32, 36; 33, 37; 34, 38; 34, 39; 35, 40; 36, 41; 37, 42; 39, 43; 39, 44; 41, 45; 41, 46; 42, 47; 42, 48; 45, 49; 45, 50; 46, 51; 47, 52; 47, 53; 48, 54; 50, 55; 50, 56 | def fake_index(in_bam, data):
"""Create a fake index file for namesorted BAMs. bais require by CWL for consistency.
"""
index_file = "%s.bai" % in_bam
if not utils.file_exists(index_file):
with file_transaction(data, index_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
out_handle.write("name sorted -- no index")
return index_file |
0, module; 1, function_definition; 2, function_name:sort; 3, parameters; 4, block; 5, identifier:in_bam; 6, identifier:config; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, assert_statement; 11, if_statement; 12, expression_statement; 13, expression_statement; 14, if_statement; 15, return_statement; 16, identifier:order; 17, string:"coordinate"; 18, identifier:out_dir; 19, None; 20, comment:"""Sort a BAM file, skipping if already present.
"""; 21, call; 22, binary_operator:"%s in not a BAM file" % in_bam; 23, call; 24, block; 25, assignment; 26, assignment; 27, not_operator; 28, block; 29, identifier:sort_file; 30, identifier:is_bam; 31, argument_list; 32, string:"%s in not a BAM file"; 33, identifier:in_bam; 34, identifier:bam_already_sorted; 35, argument_list; 36, return_statement; 37, identifier:sort_stem; 38, call; 39, identifier:sort_file; 40, binary_operator:sort_stem + ".bam"; 41, call; 42, expression_statement; 43, expression_statement; 44, with_statement; 45, identifier:in_bam; 46, identifier:in_bam; 47, identifier:config; 48, identifier:order; 49, identifier:in_bam; 50, identifier:_get_sort_stem; 51, argument_list; 52, identifier:sort_stem; 53, string:".bam"; 54, attribute; 55, argument_list; 56, assignment; 57, assignment; 58, with_clause; 59, block; 60, identifier:in_bam; 61, identifier:order; 62, identifier:out_dir; 63, identifier:utils; 64, identifier:file_exists; 65, identifier:sort_file; 66, identifier:samtools; 67, call; 68, identifier:cores; 69, call; 70, with_item; 71, expression_statement; 72, expression_statement; 73, expression_statement; 74, expression_statement; 75, comment:# Slightly decrease memory and allow more accurate representation; 76, comment:# in Mb to ensure fits within systems like SLURM; 77, expression_statement; 78, expression_statement; 79, expression_statement; 80, attribute; 81, argument_list; 82, attribute; 83, argument_list; 84, as_pattern; 85, assignment; 86, assignment; 87, assignment; 88, assignment; 89, assignment; 90, assignment; 91, call; 92, identifier:config_utils; 93, identifier:get_program; 94, string:"samtools"; 95, identifier:config; 96, subscript; 97, identifier:get; 98, string:"num_cores"; 99, integer:1; 100, call; 101, as_pattern_target; 102, identifier:tx_sort_stem; 103, subscript; 104, identifier:tx_dir; 105, call; 106, identifier:order_flag; 107, conditional_expression:"-n" if order == "queryname" else ""; 108, identifier:resources; 109, call; 110, identifier:mem; 111, call; 112, identifier:cmd; 113, parenthesized_expression; 114, attribute; 115, argument_list; 116, identifier:config; 117, string:"algorithm"; 118, identifier:file_transaction; 119, argument_list; 120, identifier:tx_sort_file; 121, call; 122, integer:0; 123, attribute; 124, argument_list; 125, string:"-n"; 126, comparison_operator:order == "queryname"; 127, string:""; 128, attribute; 129, argument_list; 130, attribute; 131, argument_list; 132, concatenated_string; 133, identifier:do; 134, identifier:run; 135, call; 136, binary_operator:"Sort BAM file %s: %s to %s" %
(order, os.path.basename(in_bam), os.path.basename(sort_file)); 137, identifier:config; 138, identifier:sort_file; 139, attribute; 140, argument_list; 141, identifier:utils; 142, identifier:safe_makedir; 143, call; 144, identifier:order; 145, string:"queryname"; 146, identifier:config_utils; 147, identifier:get_resources; 148, string:"samtools"; 149, identifier:config; 150, call; 151, identifier:upper; 152, string:"{samtools} sort -@ {cores} -m {mem} -O BAM {order_flag} "; 153, string:"-T {tx_sort_stem}-sort -o {tx_sort_file} {in_bam}"; 154, attribute; 155, argument_list; 156, string:"Sort BAM file %s: %s to %s"; 157, tuple; 158, attribute; 159, identifier:splitext; 160, identifier:tx_sort_file; 161, attribute; 162, argument_list; 163, attribute; 164, argument_list; 165, identifier:cmd; 166, identifier:format; 167, dictionary_splat; 168, identifier:order; 169, call; 170, call; 171, identifier:os; 172, identifier:path; 173, attribute; 174, identifier:dirname; 175, identifier:tx_sort_file; 176, identifier:config_utils; 177, identifier:adjust_memory; 178, call; 179, float:1.25; 180, string:"decrease"; 181, keyword_argument; 182, call; 183, attribute; 184, argument_list; 185, attribute; 186, argument_list; 187, identifier:os; 188, identifier:path; 189, attribute; 190, argument_list; 191, identifier:out_modifier; 192, string:"M"; 193, identifier:locals; 194, argument_list; 195, attribute; 196, identifier:basename; 197, identifier:in_bam; 198, attribute; 199, identifier:basename; 200, identifier:sort_file; 201, identifier:resources; 202, identifier:get; 203, string:"memory"; 204, string:"2G"; 205, identifier:os; 206, identifier:path; 207, identifier:os; 208, identifier:path | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 7, 16; 7, 17; 8, 18; 8, 19; 9, 20; 10, 21; 10, 22; 11, 23; 11, 24; 12, 25; 13, 26; 14, 27; 14, 28; 15, 29; 21, 30; 21, 31; 22, 32; 22, 33; 23, 34; 23, 35; 24, 36; 25, 37; 25, 38; 26, 39; 26, 40; 27, 41; 28, 42; 28, 43; 28, 44; 31, 45; 35, 46; 35, 47; 35, 48; 36, 49; 38, 50; 38, 51; 40, 52; 40, 53; 41, 54; 41, 55; 42, 56; 43, 57; 44, 58; 44, 59; 51, 60; 51, 61; 51, 62; 54, 63; 54, 64; 55, 65; 56, 66; 56, 67; 57, 68; 57, 69; 58, 70; 59, 71; 59, 72; 59, 73; 59, 74; 59, 75; 59, 76; 59, 77; 59, 78; 59, 79; 67, 80; 67, 81; 69, 82; 69, 83; 70, 84; 71, 85; 72, 86; 73, 87; 74, 88; 77, 89; 78, 90; 79, 91; 80, 92; 80, 93; 81, 94; 81, 95; 82, 96; 82, 97; 83, 98; 83, 99; 84, 100; 84, 101; 85, 102; 85, 103; 86, 104; 86, 105; 87, 106; 87, 107; 88, 108; 88, 109; 89, 110; 89, 111; 90, 112; 90, 113; 91, 114; 91, 115; 96, 116; 96, 117; 100, 118; 100, 119; 101, 120; 103, 121; 103, 122; 105, 123; 105, 124; 107, 125; 107, 126; 107, 127; 109, 128; 109, 129; 111, 130; 111, 131; 113, 132; 114, 133; 114, 134; 115, 135; 115, 136; 119, 137; 119, 138; 121, 139; 121, 140; 123, 141; 123, 142; 124, 143; 126, 144; 126, 145; 128, 146; 128, 147; 129, 148; 129, 149; 130, 150; 130, 151; 132, 152; 132, 153; 135, 154; 135, 155; 136, 156; 136, 157; 139, 158; 139, 159; 140, 160; 143, 161; 143, 162; 150, 163; 150, 164; 154, 165; 154, 166; 155, 167; 157, 168; 157, 169; 157, 170; 158, 171; 158, 172; 161, 173; 161, 174; 162, 175; 163, 176; 163, 177; 164, 178; 164, 179; 164, 180; 164, 181; 167, 182; 169, 183; 169, 184; 170, 185; 170, 186; 173, 187; 173, 188; 178, 189; 178, 190; 181, 191; 181, 192; 182, 193; 182, 194; 183, 195; 183, 196; 184, 197; 185, 198; 185, 199; 186, 200; 189, 201; 189, 202; 190, 203; 190, 204; 195, 205; 195, 206; 198, 207; 198, 208 | def sort(in_bam, config, order="coordinate", out_dir=None):
"""Sort a BAM file, skipping if already present.
"""
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
if bam_already_sorted(in_bam, config, order):
return in_bam
sort_stem = _get_sort_stem(in_bam, order, out_dir)
sort_file = sort_stem + ".bam"
if not utils.file_exists(sort_file):
samtools = config_utils.get_program("samtools", config)
cores = config["algorithm"].get("num_cores", 1)
with file_transaction(config, sort_file) as tx_sort_file:
tx_sort_stem = os.path.splitext(tx_sort_file)[0]
tx_dir = utils.safe_makedir(os.path.dirname(tx_sort_file))
order_flag = "-n" if order == "queryname" else ""
resources = config_utils.get_resources("samtools", config)
# Slightly decrease memory and allow more accurate representation
# in Mb to ensure fits within systems like SLURM
mem = config_utils.adjust_memory(resources.get("memory", "2G"),
1.25, "decrease", out_modifier="M").upper()
cmd = ("{samtools} sort -@ {cores} -m {mem} -O BAM {order_flag} "
"-T {tx_sort_stem}-sort -o {tx_sort_file} {in_bam}")
do.run(cmd.format(**locals()), "Sort BAM file %s: %s to %s" %
(order, os.path.basename(in_bam), os.path.basename(sort_file)))
return sort_file |
0, module; 1, function_definition; 2, function_name:tobam_cl; 3, parameters; 4, block; 5, identifier:data; 6, identifier:out_file; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, with_statement; 12, identifier:is_paired; 13, False; 14, comment:"""Prepare command line for producing de-duplicated sorted output.
- If no deduplication, sort and prepare a BAM file.
- If paired, then use samblaster and prepare discordant outputs.
- If unpaired, use biobambam's bammarkduplicates
"""; 15, assignment; 16, assignment; 17, with_clause; 18, block; 19, identifier:do_dedup; 20, call; 21, identifier:umi_consensus; 22, call; 23, with_item; 24, if_statement; 25, identifier:_check_dedup; 26, argument_list; 27, attribute; 28, argument_list; 29, as_pattern; 30, not_operator; 31, block; 32, elif_clause; 33, elif_clause; 34, else_clause; 35, identifier:data; 36, identifier:dd; 37, identifier:get_umi_consensus; 38, identifier:data; 39, call; 40, as_pattern_target; 41, identifier:do_dedup; 42, expression_statement; 43, identifier:umi_consensus; 44, block; 45, boolean_operator; 46, block; 47, block; 48, identifier:file_transaction; 49, argument_list; 50, identifier:tx_out_file; 51, yield; 52, expression_statement; 53, boolean_operator; 54, not_operator; 55, expression_statement; 56, expression_statement; 57, with_statement; 58, expression_statement; 59, identifier:data; 60, identifier:out_file; 61, tuple; 62, yield; 63, identifier:is_paired; 64, call; 65, call; 66, assignment; 67, assignment; 68, with_clause; 69, block; 70, yield; 71, call; 72, identifier:tx_out_file; 73, tuple; 74, identifier:_need_sr_disc_reads; 75, argument_list; 76, identifier:_too_many_contigs; 77, argument_list; 78, identifier:sr_file; 79, binary_operator:"%s-sr.bam" % os.path.splitext(out_file)[0]; 80, identifier:disc_file; 81, binary_operator:"%s-disc.bam" % os.path.splitext(out_file)[0]; 82, with_item; 83, with_statement; 84, tuple; 85, identifier:sam_to_sortbam_cl; 86, argument_list; 87, call; 88, identifier:tx_out_file; 89, identifier:data; 90, call; 91, string:"%s-sr.bam"; 92, subscript; 93, string:"%s-disc.bam"; 94, subscript; 95, as_pattern; 96, with_clause; 97, block; 98, call; 99, identifier:tx_out_file; 100, identifier:data; 101, identifier:tx_out_file; 102, identifier:_sam_to_grouped_umi_cl; 103, argument_list; 104, attribute; 105, argument_list; 106, call; 107, integer:0; 108, call; 109, integer:0; 110, call; 111, as_pattern_target; 112, with_item; 113, expression_statement; 114, identifier:_biobambam_dedup_sort; 115, argument_list; 116, identifier:data; 117, identifier:umi_consensus; 118, identifier:tx_out_file; 119, identifier:dd; 120, identifier:get_ref_file; 121, identifier:data; 122, attribute; 123, argument_list; 124, attribute; 125, argument_list; 126, identifier:file_transaction; 127, argument_list; 128, identifier:tx_sr_file; 129, as_pattern; 130, yield; 131, identifier:data; 132, identifier:tx_out_file; 133, attribute; 134, identifier:splitext; 135, identifier:out_file; 136, attribute; 137, identifier:splitext; 138, identifier:out_file; 139, identifier:data; 140, identifier:sr_file; 141, call; 142, as_pattern_target; 143, tuple; 144, identifier:os; 145, identifier:path; 146, identifier:os; 147, identifier:path; 148, identifier:file_transaction; 149, argument_list; 150, identifier:tx_disc_file; 151, call; 152, identifier:tx_out_file; 153, identifier:data; 154, identifier:disc_file; 155, identifier:samblaster_dedup_sort; 156, argument_list; 157, identifier:data; 158, identifier:tx_out_file; 159, identifier:tx_sr_file; 160, identifier:tx_disc_file | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 7, 12; 7, 13; 8, 14; 9, 15; 10, 16; 11, 17; 11, 18; 15, 19; 15, 20; 16, 21; 16, 22; 17, 23; 18, 24; 20, 25; 20, 26; 22, 27; 22, 28; 23, 29; 24, 30; 24, 31; 24, 32; 24, 33; 24, 34; 26, 35; 27, 36; 27, 37; 28, 38; 29, 39; 29, 40; 30, 41; 31, 42; 32, 43; 32, 44; 33, 45; 33, 46; 34, 47; 39, 48; 39, 49; 40, 50; 42, 51; 44, 52; 45, 53; 45, 54; 46, 55; 46, 56; 46, 57; 47, 58; 49, 59; 49, 60; 51, 61; 52, 62; 53, 63; 53, 64; 54, 65; 55, 66; 56, 67; 57, 68; 57, 69; 58, 70; 61, 71; 61, 72; 62, 73; 64, 74; 64, 75; 65, 76; 65, 77; 66, 78; 66, 79; 67, 80; 67, 81; 68, 82; 69, 83; 70, 84; 71, 85; 71, 86; 73, 87; 73, 88; 75, 89; 77, 90; 79, 91; 79, 92; 81, 93; 81, 94; 82, 95; 83, 96; 83, 97; 84, 98; 84, 99; 86, 100; 86, 101; 87, 102; 87, 103; 90, 104; 90, 105; 92, 106; 92, 107; 94, 108; 94, 109; 95, 110; 95, 111; 96, 112; 97, 113; 98, 114; 98, 115; 103, 116; 103, 117; 103, 118; 104, 119; 104, 120; 105, 121; 106, 122; 106, 123; 108, 124; 108, 125; 110, 126; 110, 127; 111, 128; 112, 129; 113, 130; 115, 131; 115, 132; 122, 133; 122, 134; 123, 135; 124, 136; 124, 137; 125, 138; 127, 139; 127, 140; 129, 141; 129, 142; 130, 143; 133, 144; 133, 145; 136, 146; 136, 147; 141, 148; 141, 149; 142, 150; 143, 151; 143, 152; 149, 153; 149, 154; 151, 155; 151, 156; 156, 157; 156, 158; 156, 159; 156, 160 | def tobam_cl(data, out_file, is_paired=False):
"""Prepare command line for producing de-duplicated sorted output.
- If no deduplication, sort and prepare a BAM file.
- If paired, then use samblaster and prepare discordant outputs.
- If unpaired, use biobambam's bammarkduplicates
"""
do_dedup = _check_dedup(data)
umi_consensus = dd.get_umi_consensus(data)
with file_transaction(data, out_file) as tx_out_file:
if not do_dedup:
yield (sam_to_sortbam_cl(data, tx_out_file), tx_out_file)
elif umi_consensus:
yield (_sam_to_grouped_umi_cl(data, umi_consensus, tx_out_file), tx_out_file)
elif is_paired and _need_sr_disc_reads(data) and not _too_many_contigs(dd.get_ref_file(data)):
sr_file = "%s-sr.bam" % os.path.splitext(out_file)[0]
disc_file = "%s-disc.bam" % os.path.splitext(out_file)[0]
with file_transaction(data, sr_file) as tx_sr_file:
with file_transaction(data, disc_file) as tx_disc_file:
yield (samblaster_dedup_sort(data, tx_out_file, tx_sr_file, tx_disc_file),
tx_out_file)
else:
yield (_biobambam_dedup_sort(data, tx_out_file), tx_out_file) |
0, module; 1, function_definition; 2, function_name:sam_to_sortbam_cl; 3, parameters; 4, block; 5, identifier:data; 6, identifier:tx_out_file; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, identifier:name_sort; 15, False; 16, comment:"""Convert to sorted BAM output.
Set name_sort to True to sort reads by queryname
"""; 17, assignment; 18, assignment; 19, assignment; 20, assignment; 21, parenthesized_expression; 22, identifier:samtools; 23, call; 24, pattern_list; 25, call; 26, identifier:tmp_file; 27, binary_operator:"%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]; 28, identifier:sort_flag; 29, conditional_expression:"-n" if name_sort else ""; 30, call; 31, attribute; 32, argument_list; 33, identifier:cores; 34, identifier:mem; 35, identifier:_get_cores_memory; 36, argument_list; 37, string:"%s-sorttmp"; 38, subscript; 39, string:"-n"; 40, identifier:name_sort; 41, string:""; 42, attribute; 43, argument_list; 44, identifier:config_utils; 45, identifier:get_program; 46, string:"samtools"; 47, subscript; 48, identifier:data; 49, keyword_argument; 50, call; 51, integer:0; 52, concatenated_string; 53, identifier:format; 54, dictionary_splat; 55, identifier:data; 56, string:"config"; 57, identifier:downscale; 58, integer:2; 59, attribute; 60, argument_list; 61, string:"{samtools} sort -@ {cores} -m {mem} {sort_flag} "; 62, string:"-T {tmp_file} -o {tx_out_file} /dev/stdin"; 63, call; 64, identifier:utils; 65, identifier:splitext_plus; 66, identifier:tx_out_file; 67, identifier:locals; 68, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 7, 14; 7, 15; 8, 16; 9, 17; 10, 18; 11, 19; 12, 20; 13, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 19, 27; 20, 28; 20, 29; 21, 30; 23, 31; 23, 32; 24, 33; 24, 34; 25, 35; 25, 36; 27, 37; 27, 38; 29, 39; 29, 40; 29, 41; 30, 42; 30, 43; 31, 44; 31, 45; 32, 46; 32, 47; 36, 48; 36, 49; 38, 50; 38, 51; 42, 52; 42, 53; 43, 54; 47, 55; 47, 56; 49, 57; 49, 58; 50, 59; 50, 60; 52, 61; 52, 62; 54, 63; 59, 64; 59, 65; 60, 66; 63, 67; 63, 68 | def sam_to_sortbam_cl(data, tx_out_file, name_sort=False):
"""Convert to sorted BAM output.
Set name_sort to True to sort reads by queryname
"""
samtools = config_utils.get_program("samtools", data["config"])
cores, mem = _get_cores_memory(data, downscale=2)
tmp_file = "%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]
sort_flag = "-n" if name_sort else ""
return ("{samtools} sort -@ {cores} -m {mem} {sort_flag} "
"-T {tmp_file} -o {tx_out_file} /dev/stdin".format(**locals())) |
0, module; 1, function_definition; 2, function_name:samblaster_dedup_sort; 3, parameters; 4, block; 5, identifier:data; 6, identifier:tx_out_file; 7, identifier:tx_sr_file; 8, identifier:tx_disc_file; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, comment:# full BAM -- associate more memory and cores; 15, expression_statement; 16, comment:# Potentially downsample to maximum coverage here if not splitting and whole genome sample; 17, expression_statement; 18, expression_statement; 19, if_statement; 20, comment:# split and discordant BAMs -- give less memory/cores since smaller files; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, expression_statement; 25, comment:# samblaster 0.1.22 and better require the -M flag for compatibility with bwa-mem; 26, expression_statement; 27, return_statement; 28, comment:"""Deduplicate and sort with samblaster, produces split read and discordant pair files.
"""; 29, assignment; 30, assignment; 31, assignment; 32, assignment; 33, assignment; 34, assignment; 35, assignment; 36, identifier:ds_cmd; 37, block; 38, else_clause; 39, assignment; 40, assignment; 41, assignment; 42, assignment; 43, assignment; 44, call; 45, identifier:samblaster; 46, call; 47, identifier:samtools; 48, call; 49, identifier:tmp_prefix; 50, binary_operator:"%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]; 51, identifier:tobam_cmd; 52, parenthesized_expression; 53, pattern_list; 54, call; 55, identifier:ds_cmd; 56, conditional_expression:None if data.get("align_split") else bam.get_maxcov_downsample_cl(data, "samtools"); 57, identifier:sort_opt; 58, conditional_expression:"-n" if data.get("align_split") and dd.get_mark_duplicates(data) else ""; 59, expression_statement; 60, block; 61, identifier:sort_opt; 62, string:""; 63, pattern_list; 64, call; 65, identifier:splitter_cmd; 66, call; 67, identifier:discordant_cmd; 68, call; 69, identifier:cmd; 70, parenthesized_expression; 71, attribute; 72, argument_list; 73, attribute; 74, argument_list; 75, attribute; 76, argument_list; 77, string:"%s-sorttmp"; 78, subscript; 79, string:"{samtools} sort {sort_opt} -@ {cores} -m {mem} -T {tmp_prefix}-{dext} {out_file} -"; 80, identifier:cores; 81, identifier:mem; 82, identifier:_get_cores_memory; 83, argument_list; 84, None; 85, call; 86, call; 87, string:"-n"; 88, boolean_operator; 89, string:""; 90, assignment; 91, expression_statement; 92, identifier:cores; 93, identifier:mem; 94, identifier:_get_cores_memory; 95, argument_list; 96, attribute; 97, argument_list; 98, attribute; 99, argument_list; 100, concatenated_string; 101, identifier:cmd; 102, identifier:format; 103, dictionary_splat; 104, identifier:config_utils; 105, identifier:get_program; 106, string:"samblaster"; 107, subscript; 108, identifier:config_utils; 109, identifier:get_program; 110, string:"samtools"; 111, subscript; 112, call; 113, integer:0; 114, identifier:data; 115, keyword_argument; 116, attribute; 117, argument_list; 118, attribute; 119, argument_list; 120, call; 121, call; 122, identifier:dedup_cmd; 123, binary_operator:"%s %s > %s" % (tobam_cmd.format(out_file="", dext="full", **locals()), ds_cmd, tx_out_file); 124, assignment; 125, identifier:data; 126, keyword_argument; 127, identifier:tobam_cmd; 128, identifier:format; 129, keyword_argument; 130, keyword_argument; 131, dictionary_splat; 132, identifier:tobam_cmd; 133, identifier:format; 134, keyword_argument; 135, keyword_argument; 136, dictionary_splat; 137, string:"{samblaster} --addMateTags -M --splitterFile >({splitter_cmd}) --discordantFile >({discordant_cmd}) "; 138, string:"| {dedup_cmd}"; 139, call; 140, identifier:data; 141, string:"config"; 142, identifier:data; 143, string:"config"; 144, attribute; 145, argument_list; 146, identifier:downscale; 147, integer:2; 148, identifier:data; 149, identifier:get; 150, string:"align_split"; 151, identifier:bam; 152, identifier:get_maxcov_downsample_cl; 153, identifier:data; 154, string:"samtools"; 155, attribute; 156, argument_list; 157, attribute; 158, argument_list; 159, string:"%s %s > %s"; 160, tuple; 161, identifier:dedup_cmd; 162, call; 163, identifier:downscale; 164, integer:4; 165, identifier:out_file; 166, binary_operator:"-o %s" % tx_sr_file; 167, identifier:dext; 168, string:"spl"; 169, call; 170, identifier:out_file; 171, binary_operator:"-o %s" % tx_disc_file; 172, identifier:dext; 173, string:"disc"; 174, call; 175, identifier:locals; 176, argument_list; 177, identifier:utils; 178, identifier:splitext_plus; 179, identifier:tx_out_file; 180, identifier:data; 181, identifier:get; 182, string:"align_split"; 183, identifier:dd; 184, identifier:get_mark_duplicates; 185, identifier:data; 186, call; 187, identifier:ds_cmd; 188, identifier:tx_out_file; 189, attribute; 190, argument_list; 191, string:"-o %s"; 192, identifier:tx_sr_file; 193, identifier:locals; 194, argument_list; 195, string:"-o %s"; 196, identifier:tx_disc_file; 197, identifier:locals; 198, argument_list; 199, attribute; 200, argument_list; 201, identifier:tobam_cmd; 202, identifier:format; 203, keyword_argument; 204, keyword_argument; 205, dictionary_splat; 206, identifier:tobam_cmd; 207, identifier:format; 208, keyword_argument; 209, keyword_argument; 210, dictionary_splat; 211, identifier:out_file; 212, binary_operator:"-o %s" % tx_out_file; 213, identifier:dext; 214, string:"full"; 215, call; 216, identifier:out_file; 217, string:""; 218, identifier:dext; 219, string:"full"; 220, call; 221, string:"-o %s"; 222, identifier:tx_out_file; 223, identifier:locals; 224, argument_list; 225, identifier:locals; 226, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 9, 28; 10, 29; 11, 30; 12, 31; 13, 32; 15, 33; 17, 34; 18, 35; 19, 36; 19, 37; 19, 38; 21, 39; 22, 40; 23, 41; 24, 42; 26, 43; 27, 44; 29, 45; 29, 46; 30, 47; 30, 48; 31, 49; 31, 50; 32, 51; 32, 52; 33, 53; 33, 54; 34, 55; 34, 56; 35, 57; 35, 58; 37, 59; 38, 60; 39, 61; 39, 62; 40, 63; 40, 64; 41, 65; 41, 66; 42, 67; 42, 68; 43, 69; 43, 70; 44, 71; 44, 72; 46, 73; 46, 74; 48, 75; 48, 76; 50, 77; 50, 78; 52, 79; 53, 80; 53, 81; 54, 82; 54, 83; 56, 84; 56, 85; 56, 86; 58, 87; 58, 88; 58, 89; 59, 90; 60, 91; 63, 92; 63, 93; 64, 94; 64, 95; 66, 96; 66, 97; 68, 98; 68, 99; 70, 100; 71, 101; 71, 102; 72, 103; 73, 104; 73, 105; 74, 106; 74, 107; 75, 108; 75, 109; 76, 110; 76, 111; 78, 112; 78, 113; 83, 114; 83, 115; 85, 116; 85, 117; 86, 118; 86, 119; 88, 120; 88, 121; 90, 122; 90, 123; 91, 124; 95, 125; 95, 126; 96, 127; 96, 128; 97, 129; 97, 130; 97, 131; 98, 132; 98, 133; 99, 134; 99, 135; 99, 136; 100, 137; 100, 138; 103, 139; 107, 140; 107, 141; 111, 142; 111, 143; 112, 144; 112, 145; 115, 146; 115, 147; 116, 148; 116, 149; 117, 150; 118, 151; 118, 152; 119, 153; 119, 154; 120, 155; 120, 156; 121, 157; 121, 158; 123, 159; 123, 160; 124, 161; 124, 162; 126, 163; 126, 164; 129, 165; 129, 166; 130, 167; 130, 168; 131, 169; 134, 170; 134, 171; 135, 172; 135, 173; 136, 174; 139, 175; 139, 176; 144, 177; 144, 178; 145, 179; 155, 180; 155, 181; 156, 182; 157, 183; 157, 184; 158, 185; 160, 186; 160, 187; 160, 188; 162, 189; 162, 190; 166, 191; 166, 192; 169, 193; 169, 194; 171, 195; 171, 196; 174, 197; 174, 198; 186, 199; 186, 200; 189, 201; 189, 202; 190, 203; 190, 204; 190, 205; 199, 206; 199, 207; 200, 208; 200, 209; 200, 210; 203, 211; 203, 212; 204, 213; 204, 214; 205, 215; 208, 216; 208, 217; 209, 218; 209, 219; 210, 220; 212, 221; 212, 222; 215, 223; 215, 224; 220, 225; 220, 226 | def samblaster_dedup_sort(data, tx_out_file, tx_sr_file, tx_disc_file):
"""Deduplicate and sort with samblaster, produces split read and discordant pair files.
"""
samblaster = config_utils.get_program("samblaster", data["config"])
samtools = config_utils.get_program("samtools", data["config"])
tmp_prefix = "%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]
tobam_cmd = ("{samtools} sort {sort_opt} -@ {cores} -m {mem} -T {tmp_prefix}-{dext} {out_file} -")
# full BAM -- associate more memory and cores
cores, mem = _get_cores_memory(data, downscale=2)
# Potentially downsample to maximum coverage here if not splitting and whole genome sample
ds_cmd = None if data.get("align_split") else bam.get_maxcov_downsample_cl(data, "samtools")
sort_opt = "-n" if data.get("align_split") and dd.get_mark_duplicates(data) else ""
if ds_cmd:
dedup_cmd = "%s %s > %s" % (tobam_cmd.format(out_file="", dext="full", **locals()), ds_cmd, tx_out_file)
else:
dedup_cmd = tobam_cmd.format(out_file="-o %s" % tx_out_file, dext="full", **locals())
# split and discordant BAMs -- give less memory/cores since smaller files
sort_opt = ""
cores, mem = _get_cores_memory(data, downscale=4)
splitter_cmd = tobam_cmd.format(out_file="-o %s" % tx_sr_file, dext="spl", **locals())
discordant_cmd = tobam_cmd.format(out_file="-o %s" % tx_disc_file, dext="disc", **locals())
# samblaster 0.1.22 and better require the -M flag for compatibility with bwa-mem
cmd = ("{samblaster} --addMateTags -M --splitterFile >({splitter_cmd}) --discordantFile >({discordant_cmd}) "
"| {dedup_cmd}")
return cmd.format(**locals()) |
0, module; 1, function_definition; 2, function_name:_biobambam_dedup_sort; 3, parameters; 4, block; 5, identifier:data; 6, identifier:tx_out_file; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, return_statement; 13, comment:"""Perform streaming deduplication and sorting with biobambam's bamsormadup
"""; 14, assignment; 15, assignment; 16, assignment; 17, call; 18, block; 19, else_clause; 20, call; 21, identifier:samtools; 22, call; 23, pattern_list; 24, call; 25, identifier:tmp_file; 26, binary_operator:"%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]; 27, attribute; 28, argument_list; 29, expression_statement; 30, expression_statement; 31, comment:# scale core usage to avoid memory issues with larger WGS samples; 32, block; 33, attribute; 34, argument_list; 35, attribute; 36, argument_list; 37, identifier:cores; 38, identifier:mem; 39, identifier:_get_cores_memory; 40, argument_list; 41, string:"%s-sorttmp"; 42, subscript; 43, identifier:data; 44, identifier:get; 45, string:"align_split"; 46, assignment; 47, assignment; 48, expression_statement; 49, expression_statement; 50, expression_statement; 51, expression_statement; 52, identifier:cmd; 53, identifier:format; 54, dictionary_splat; 55, identifier:config_utils; 56, identifier:get_program; 57, string:"samtools"; 58, subscript; 59, identifier:data; 60, keyword_argument; 61, call; 62, integer:0; 63, identifier:sort_opt; 64, conditional_expression:"-n" if data.get("align_split") and _check_dedup(data) else ""; 65, identifier:cmd; 66, binary_operator:"{samtools} sort %s -@ {cores} -m {mem} -O bam -T {tmp_file}-namesort -o {tx_out_file} -" % sort_opt; 67, assignment; 68, assignment; 69, assignment; 70, assignment; 71, call; 72, identifier:data; 73, string:"config"; 74, identifier:downscale; 75, integer:2; 76, attribute; 77, argument_list; 78, string:"-n"; 79, boolean_operator; 80, string:""; 81, string:"{samtools} sort %s -@ {cores} -m {mem} -O bam -T {tmp_file}-namesort -o {tx_out_file} -"; 82, identifier:sort_opt; 83, identifier:cores; 84, call; 85, identifier:ds_cmd; 86, call; 87, identifier:bamsormadup; 88, call; 89, identifier:cmd; 90, parenthesized_expression; 91, identifier:locals; 92, argument_list; 93, identifier:utils; 94, identifier:splitext_plus; 95, identifier:tx_out_file; 96, call; 97, call; 98, identifier:max; 99, argument_list; 100, attribute; 101, argument_list; 102, attribute; 103, argument_list; 104, binary_operator:"{bamsormadup} inputformat=sam threads={cores} tmpfile={tmp_file}-markdup "
"SO=coordinate %s > {tx_out_file}" % ds_cmd; 105, attribute; 106, argument_list; 107, identifier:_check_dedup; 108, argument_list; 109, integer:1; 110, call; 111, identifier:bam; 112, identifier:get_maxcov_downsample_cl; 113, identifier:data; 114, string:"bamsormadup"; 115, identifier:config_utils; 116, identifier:get_program; 117, string:"bamsormadup"; 118, identifier:data; 119, concatenated_string; 120, identifier:ds_cmd; 121, identifier:data; 122, identifier:get; 123, string:"align_split"; 124, identifier:data; 125, identifier:int; 126, argument_list; 127, string:"{bamsormadup} inputformat=sam threads={cores} tmpfile={tmp_file}-markdup "; 128, string:"SO=coordinate %s > {tx_out_file}"; 129, call; 130, attribute; 131, argument_list; 132, identifier:math; 133, identifier:ceil; 134, binary_operator:cores * 0.75; 135, identifier:cores; 136, float:0.75 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 8, 14; 9, 15; 10, 16; 11, 17; 11, 18; 11, 19; 12, 20; 14, 21; 14, 22; 15, 23; 15, 24; 16, 25; 16, 26; 17, 27; 17, 28; 18, 29; 18, 30; 19, 31; 19, 32; 20, 33; 20, 34; 22, 35; 22, 36; 23, 37; 23, 38; 24, 39; 24, 40; 26, 41; 26, 42; 27, 43; 27, 44; 28, 45; 29, 46; 30, 47; 32, 48; 32, 49; 32, 50; 32, 51; 33, 52; 33, 53; 34, 54; 35, 55; 35, 56; 36, 57; 36, 58; 40, 59; 40, 60; 42, 61; 42, 62; 46, 63; 46, 64; 47, 65; 47, 66; 48, 67; 49, 68; 50, 69; 51, 70; 54, 71; 58, 72; 58, 73; 60, 74; 60, 75; 61, 76; 61, 77; 64, 78; 64, 79; 64, 80; 66, 81; 66, 82; 67, 83; 67, 84; 68, 85; 68, 86; 69, 87; 69, 88; 70, 89; 70, 90; 71, 91; 71, 92; 76, 93; 76, 94; 77, 95; 79, 96; 79, 97; 84, 98; 84, 99; 86, 100; 86, 101; 88, 102; 88, 103; 90, 104; 96, 105; 96, 106; 97, 107; 97, 108; 99, 109; 99, 110; 100, 111; 100, 112; 101, 113; 101, 114; 102, 115; 102, 116; 103, 117; 103, 118; 104, 119; 104, 120; 105, 121; 105, 122; 106, 123; 108, 124; 110, 125; 110, 126; 119, 127; 119, 128; 126, 129; 129, 130; 129, 131; 130, 132; 130, 133; 131, 134; 134, 135; 134, 136 | def _biobambam_dedup_sort(data, tx_out_file):
"""Perform streaming deduplication and sorting with biobambam's bamsormadup
"""
samtools = config_utils.get_program("samtools", data["config"])
cores, mem = _get_cores_memory(data, downscale=2)
tmp_file = "%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]
if data.get("align_split"):
sort_opt = "-n" if data.get("align_split") and _check_dedup(data) else ""
cmd = "{samtools} sort %s -@ {cores} -m {mem} -O bam -T {tmp_file}-namesort -o {tx_out_file} -" % sort_opt
else:
# scale core usage to avoid memory issues with larger WGS samples
cores = max(1, int(math.ceil(cores * 0.75)))
ds_cmd = bam.get_maxcov_downsample_cl(data, "bamsormadup")
bamsormadup = config_utils.get_program("bamsormadup", data)
cmd = ("{bamsormadup} inputformat=sam threads={cores} tmpfile={tmp_file}-markdup "
"SO=coordinate %s > {tx_out_file}" % ds_cmd)
return cmd.format(**locals()) |
0, module; 1, function_definition; 2, function_name:_prepare_bam_file; 3, parameters; 4, block; 5, identifier:bam_file; 6, identifier:tmp_dir; 7, identifier:config; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, return_statement; 12, comment:"""
Pipe sort by name cmd in case sort by coordinates
"""; 13, assignment; 14, comparison_operator:sort_mode != "queryname"; 15, block; 16, identifier:bam_file; 17, identifier:sort_mode; 18, call; 19, identifier:sort_mode; 20, string:"queryname"; 21, expression_statement; 22, identifier:_get_sort_order; 23, argument_list; 24, assignment; 25, identifier:bam_file; 26, identifier:config; 27, identifier:bam_file; 28, call; 29, identifier:sort; 30, argument_list; 31, identifier:bam_file; 32, identifier:config; 33, string:"queryname" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 8, 12; 9, 13; 10, 14; 10, 15; 11, 16; 13, 17; 13, 18; 14, 19; 14, 20; 15, 21; 18, 22; 18, 23; 21, 24; 23, 25; 23, 26; 24, 27; 24, 28; 28, 29; 28, 30; 30, 31; 30, 32; 30, 33 | def _prepare_bam_file(bam_file, tmp_dir, config):
"""
Pipe sort by name cmd in case sort by coordinates
"""
sort_mode = _get_sort_order(bam_file, config)
if sort_mode != "queryname":
bam_file = sort(bam_file, config, "queryname")
return bam_file |
0, module; 1, function_definition; 2, function_name:_concat_records; 3, parameters; 4, block; 5, identifier:items_by_key; 6, identifier:input_order; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, expression_statement; 11, expression_statement; 12, if_statement; 13, return_statement; 14, comment:"""Concatenate records into a single key to avoid merging.
Handles heterogeneous records that will then be sorted out in
the processing fuction.
"""; 15, assignment; 16, tuple_pattern; 17, call; 18, block; 19, assignment; 20, assignment; 21, comparison_operator:len(all_records) > 1; 22, block; 23, expression_list; 24, identifier:all_records; 25, list; 26, identifier:k; 27, identifier:t; 28, attribute; 29, argument_list; 30, if_statement; 31, identifier:out_items_by_key; 32, call; 33, identifier:out_input_order; 34, call; 35, call; 36, integer:1; 37, expression_statement; 38, expression_statement; 39, for_statement; 40, expression_statement; 41, identifier:out_items_by_key; 42, identifier:out_input_order; 43, identifier:input_order; 44, identifier:items; 45, comparison_operator:t == "record"; 46, block; 47, attribute; 48, argument_list; 49, attribute; 50, argument_list; 51, identifier:len; 52, argument_list; 53, assignment; 54, assignment; 55, identifier:k; 56, subscript; 57, block; 58, assignment; 59, identifier:t; 60, string:"record"; 61, expression_statement; 62, identifier:utils; 63, identifier:deepish_copy; 64, identifier:items_by_key; 65, identifier:utils; 66, identifier:deepish_copy; 67, identifier:input_order; 68, identifier:all_records; 69, identifier:final_k; 70, subscript; 71, identifier:final_v; 72, subscript; 73, identifier:all_records; 74, slice; 75, expression_statement; 76, delete_statement; 77, delete_statement; 78, subscript; 79, identifier:final_v; 80, call; 81, identifier:all_records; 82, integer:0; 83, identifier:items_by_key; 84, identifier:final_k; 85, integer:1; 86, augmented_assignment; 87, subscript; 88, subscript; 89, identifier:out_items_by_key; 90, identifier:final_k; 91, attribute; 92, argument_list; 93, identifier:final_v; 94, subscript; 95, identifier:out_items_by_key; 96, identifier:k; 97, identifier:out_input_order; 98, identifier:k; 99, identifier:all_records; 100, identifier:append; 101, identifier:k; 102, identifier:items_by_key; 103, identifier:k | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 7, 14; 8, 15; 9, 16; 9, 17; 9, 18; 10, 19; 11, 20; 12, 21; 12, 22; 13, 23; 15, 24; 15, 25; 16, 26; 16, 27; 17, 28; 17, 29; 18, 30; 19, 31; 19, 32; 20, 33; 20, 34; 21, 35; 21, 36; 22, 37; 22, 38; 22, 39; 22, 40; 23, 41; 23, 42; 28, 43; 28, 44; 30, 45; 30, 46; 32, 47; 32, 48; 34, 49; 34, 50; 35, 51; 35, 52; 37, 53; 38, 54; 39, 55; 39, 56; 39, 57; 40, 58; 45, 59; 45, 60; 46, 61; 47, 62; 47, 63; 48, 64; 49, 65; 49, 66; 50, 67; 52, 68; 53, 69; 53, 70; 54, 71; 54, 72; 56, 73; 56, 74; 57, 75; 57, 76; 57, 77; 58, 78; 58, 79; 61, 80; 70, 81; 70, 82; 72, 83; 72, 84; 74, 85; 75, 86; 76, 87; 77, 88; 78, 89; 78, 90; 80, 91; 80, 92; 86, 93; 86, 94; 87, 95; 87, 96; 88, 97; 88, 98; 91, 99; 91, 100; 92, 101; 94, 102; 94, 103 | def _concat_records(items_by_key, input_order):
"""Concatenate records into a single key to avoid merging.
Handles heterogeneous records that will then be sorted out in
the processing fuction.
"""
all_records = []
for (k, t) in input_order.items():
if t == "record":
all_records.append(k)
out_items_by_key = utils.deepish_copy(items_by_key)
out_input_order = utils.deepish_copy(input_order)
if len(all_records) > 1:
final_k = all_records[0]
final_v = items_by_key[final_k]
for k in all_records[1:]:
final_v += items_by_key[k]
del out_items_by_key[k]
del out_input_order[k]
out_items_by_key[final_k] = final_v
return out_items_by_key, out_input_order |
0, module; 1, function_definition; 2, function_name:_combine_files; 3, parameters; 4, block; 5, identifier:tsv_files; 6, identifier:work_dir; 7, identifier:data; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, if_statement; 13, return_statement; 14, comment:"""Combine multiple priority tsv files into a final sorted output.
"""; 15, assignment; 16, assignment; 17, assignment; 18, not_operator; 19, block; 20, identifier:out_file; 21, identifier:header; 22, call; 23, identifier:sample; 24, call; 25, identifier:out_file; 26, call; 27, call; 28, with_statement; 29, attribute; 30, argument_list; 31, attribute; 32, argument_list; 33, attribute; 34, argument_list; 35, attribute; 36, argument_list; 37, with_clause; 38, block; 39, string:"\t"; 40, identifier:join; 41, list; 42, identifier:dd; 43, identifier:get_sample_name; 44, identifier:data; 45, attribute; 46, identifier:join; 47, identifier:work_dir; 48, binary_operator:"%s-prioritize.tsv" % (sample); 49, identifier:utils; 50, identifier:file_exists; 51, identifier:out_file; 52, with_item; 53, expression_statement; 54, expression_statement; 55, expression_statement; 56, expression_statement; 57, expression_statement; 58, string:"caller"; 59, string:"sample"; 60, string:"chrom"; 61, string:"start"; 62, string:"end"; 63, string:"svtype"; 64, string:"lof"; 65, string:"annotation"; 66, string:"split_read_support"; 67, string:"paired_support_PE"; 68, string:"paired_support_PR"; 69, identifier:os; 70, identifier:path; 71, string:"%s-prioritize.tsv"; 72, parenthesized_expression; 73, as_pattern; 74, assignment; 75, assignment; 76, assignment; 77, assignment; 78, call; 79, identifier:sample; 80, call; 81, as_pattern_target; 82, identifier:tmpdir; 83, call; 84, identifier:input_files; 85, call; 86, identifier:sort_cmd; 87, call; 88, identifier:cmd; 89, string:"{{ echo '{header}'; cat {input_files} | {sort_cmd} -k3,3 -k4,4n; }} > {tx_out_file}"; 90, attribute; 91, argument_list; 92, identifier:file_transaction; 93, argument_list; 94, identifier:tx_out_file; 95, attribute; 96, argument_list; 97, attribute; 98, argument_list; 99, attribute; 100, argument_list; 101, identifier:do; 102, identifier:run; 103, call; 104, string:"Combine prioritized from multiple callers"; 105, identifier:data; 106, identifier:out_file; 107, attribute; 108, identifier:dirname; 109, identifier:tx_out_file; 110, string:" "; 111, identifier:join; 112, identifier:tsv_files; 113, identifier:bedutils; 114, identifier:get_sort_cmd; 115, identifier:tmpdir; 116, attribute; 117, argument_list; 118, identifier:os; 119, identifier:path; 120, identifier:cmd; 121, identifier:format; 122, dictionary_splat; 123, call; 124, identifier:locals; 125, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 8, 14; 9, 15; 10, 16; 11, 17; 12, 18; 12, 19; 13, 20; 15, 21; 15, 22; 16, 23; 16, 24; 17, 25; 17, 26; 18, 27; 19, 28; 22, 29; 22, 30; 24, 31; 24, 32; 26, 33; 26, 34; 27, 35; 27, 36; 28, 37; 28, 38; 29, 39; 29, 40; 30, 41; 31, 42; 31, 43; 32, 44; 33, 45; 33, 46; 34, 47; 34, 48; 35, 49; 35, 50; 36, 51; 37, 52; 38, 53; 38, 54; 38, 55; 38, 56; 38, 57; 41, 58; 41, 59; 41, 60; 41, 61; 41, 62; 41, 63; 41, 64; 41, 65; 41, 66; 41, 67; 41, 68; 45, 69; 45, 70; 48, 71; 48, 72; 52, 73; 53, 74; 54, 75; 55, 76; 56, 77; 57, 78; 72, 79; 73, 80; 73, 81; 74, 82; 74, 83; 75, 84; 75, 85; 76, 86; 76, 87; 77, 88; 77, 89; 78, 90; 78, 91; 80, 92; 80, 93; 81, 94; 83, 95; 83, 96; 85, 97; 85, 98; 87, 99; 87, 100; 90, 101; 90, 102; 91, 103; 91, 104; 93, 105; 93, 106; 95, 107; 95, 108; 96, 109; 97, 110; 97, 111; 98, 112; 99, 113; 99, 114; 100, 115; 103, 116; 103, 117; 107, 118; 107, 119; 116, 120; 116, 121; 117, 122; 122, 123; 123, 124; 123, 125 | def _combine_files(tsv_files, work_dir, data):
"""Combine multiple priority tsv files into a final sorted output.
"""
header = "\t".join(["caller", "sample", "chrom", "start", "end", "svtype",
"lof", "annotation", "split_read_support", "paired_support_PE", "paired_support_PR"])
sample = dd.get_sample_name(data)
out_file = os.path.join(work_dir, "%s-prioritize.tsv" % (sample))
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
tmpdir = os.path.dirname(tx_out_file)
input_files = " ".join(tsv_files)
sort_cmd = bedutils.get_sort_cmd(tmpdir)
cmd = "{{ echo '{header}'; cat {input_files} | {sort_cmd} -k3,3 -k4,4n; }} > {tx_out_file}"
do.run(cmd.format(**locals()), "Combine prioritized from multiple callers")
return out_file |
0, module; 1, function_definition; 2, function_name:sort_filenames; 3, parameters; 4, block; 5, identifier:filenames; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, comment:"""
sort a list of files by filename only, ignoring the directory names
"""; 11, assignment; 12, assignment; 13, list_comprehension; 14, identifier:basenames; 15, list_comprehension; 16, identifier:indexes; 17, list_comprehension; 18, subscript; 19, for_in_clause; 20, call; 21, for_in_clause; 22, subscript; 23, for_in_clause; 24, identifier:filenames; 25, identifier:x; 26, identifier:x; 27, identifier:indexes; 28, attribute; 29, argument_list; 30, identifier:x; 31, identifier:filenames; 32, identifier:i; 33, integer:0; 34, identifier:i; 35, call; 36, attribute; 37, identifier:basename; 38, identifier:x; 39, identifier:sorted; 40, argument_list; 41, identifier:os; 42, identifier:path; 43, call; 44, keyword_argument; 45, identifier:enumerate; 46, argument_list; 47, identifier:key; 48, lambda; 49, identifier:basenames; 50, lambda_parameters; 51, subscript; 52, identifier:x; 53, identifier:x; 54, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 9, 13; 11, 14; 11, 15; 12, 16; 12, 17; 13, 18; 13, 19; 15, 20; 15, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 19, 27; 20, 28; 20, 29; 21, 30; 21, 31; 22, 32; 22, 33; 23, 34; 23, 35; 28, 36; 28, 37; 29, 38; 35, 39; 35, 40; 36, 41; 36, 42; 40, 43; 40, 44; 43, 45; 43, 46; 44, 47; 44, 48; 46, 49; 48, 50; 48, 51; 50, 52; 51, 53; 51, 54 | def sort_filenames(filenames):
"""
sort a list of files by filename only, ignoring the directory names
"""
basenames = [os.path.basename(x) for x in filenames]
indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])]
return [filenames[x] for x in indexes] |
0, module; 1, function_definition; 2, function_name:sort_csv; 3, parameters; 4, block; 5, identifier:in_file; 6, expression_statement; 7, expression_statement; 8, if_statement; 9, return_statement; 10, comment:"""Sort a CSV file by read name, allowing direct comparison.
"""; 11, assignment; 12, not_operator; 13, block; 14, identifier:out_file; 15, identifier:out_file; 16, binary_operator:"%s.sort" % in_file; 17, parenthesized_expression; 18, expression_statement; 19, with_statement; 20, string:"%s.sort"; 21, identifier:in_file; 22, boolean_operator; 23, assignment; 24, with_clause; 25, block; 26, call; 27, comparison_operator:os.path.getsize(out_file) > 0; 28, identifier:cl; 29, list; 30, with_item; 31, expression_statement; 32, expression_statement; 33, attribute; 34, argument_list; 35, call; 36, integer:0; 37, string:"sort"; 38, string:"-k"; 39, string:"1,1"; 40, identifier:in_file; 41, as_pattern; 42, assignment; 43, call; 44, attribute; 45, identifier:exists; 46, identifier:out_file; 47, attribute; 48, argument_list; 49, call; 50, as_pattern_target; 51, identifier:child; 52, call; 53, attribute; 54, argument_list; 55, identifier:os; 56, identifier:path; 57, attribute; 58, identifier:getsize; 59, identifier:out_file; 60, identifier:open; 61, argument_list; 62, identifier:out_handle; 63, attribute; 64, argument_list; 65, identifier:child; 66, identifier:wait; 67, identifier:os; 68, identifier:path; 69, identifier:out_file; 70, string:"w"; 71, identifier:subprocess; 72, identifier:Popen; 73, identifier:cl; 74, keyword_argument; 75, identifier:stdout; 76, identifier:out_handle | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 9, 14; 11, 15; 11, 16; 12, 17; 13, 18; 13, 19; 16, 20; 16, 21; 17, 22; 18, 23; 19, 24; 19, 25; 22, 26; 22, 27; 23, 28; 23, 29; 24, 30; 25, 31; 25, 32; 26, 33; 26, 34; 27, 35; 27, 36; 29, 37; 29, 38; 29, 39; 29, 40; 30, 41; 31, 42; 32, 43; 33, 44; 33, 45; 34, 46; 35, 47; 35, 48; 41, 49; 41, 50; 42, 51; 42, 52; 43, 53; 43, 54; 44, 55; 44, 56; 47, 57; 47, 58; 48, 59; 49, 60; 49, 61; 50, 62; 52, 63; 52, 64; 53, 65; 53, 66; 57, 67; 57, 68; 61, 69; 61, 70; 63, 71; 63, 72; 64, 73; 64, 74; 74, 75; 74, 76 | def sort_csv(in_file):
"""Sort a CSV file by read name, allowing direct comparison.
"""
out_file = "%s.sort" % in_file
if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0):
cl = ["sort", "-k", "1,1", in_file]
with open(out_file, "w") as out_handle:
child = subprocess.Popen(cl, stdout=out_handle)
child.wait()
return out_file |
0, module; 1, function_definition; 2, function_name:hydra_to_vcf_writer; 3, parameters; 4, block; 5, identifier:hydra_file; 6, identifier:genome_2bit; 7, identifier:options; 8, identifier:out_handle; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, for_statement; 14, comment:"""Write hydra output as sorted VCF file.
Requires loading the hydra file into memory to perform sorting
on output VCF. Could generalize this to no sorting or by-chromosome
approach if this proves too memory intensive.
"""; 15, call; 16, assignment; 17, call; 18, identifier:brend; 19, identifier:brends; 20, block; 21, identifier:_write_vcf_header; 22, argument_list; 23, identifier:brends; 24, call; 25, attribute; 26, argument_list; 27, expression_statement; 28, identifier:out_handle; 29, identifier:list; 30, argument_list; 31, identifier:brends; 32, identifier:sort; 33, keyword_argument; 34, call; 35, call; 36, identifier:key; 37, call; 38, identifier:_write_vcf_breakend; 39, argument_list; 40, identifier:_get_vcf_breakends; 41, argument_list; 42, identifier:attrgetter; 43, argument_list; 44, identifier:brend; 45, identifier:out_handle; 46, identifier:hydra_file; 47, identifier:genome_2bit; 48, identifier:options; 49, string:"chrom"; 50, string:"pos" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 9, 14; 10, 15; 11, 16; 12, 17; 13, 18; 13, 19; 13, 20; 15, 21; 15, 22; 16, 23; 16, 24; 17, 25; 17, 26; 20, 27; 22, 28; 24, 29; 24, 30; 25, 31; 25, 32; 26, 33; 27, 34; 30, 35; 33, 36; 33, 37; 34, 38; 34, 39; 35, 40; 35, 41; 37, 42; 37, 43; 39, 44; 39, 45; 41, 46; 41, 47; 41, 48; 43, 49; 43, 50 | def hydra_to_vcf_writer(hydra_file, genome_2bit, options, out_handle):
"""Write hydra output as sorted VCF file.
Requires loading the hydra file into memory to perform sorting
on output VCF. Could generalize this to no sorting or by-chromosome
approach if this proves too memory intensive.
"""
_write_vcf_header(out_handle)
brends = list(_get_vcf_breakends(hydra_file, genome_2bit, options))
brends.sort(key=attrgetter("chrom", "pos"))
for brend in brends:
_write_vcf_breakend(brend, out_handle) |
0, module; 1, function_definition; 2, function_name:_split_by_ready_regions; 3, parameters; 4, block; 5, identifier:ext; 6, identifier:file_key; 7, identifier:dir_ext_fn; 8, expression_statement; 9, function_definition; 10, function_definition; 11, function_definition; 12, return_statement; 13, comment:"""Organize splits based on regions generated by parallel_prep_region.
Sort splits so largest regions analyzed first, avoiding potentially lagging runs
at end.
"""; 14, function_name:_sort_by_size; 15, parameters; 16, block; 17, function_name:_assign_bams_to_regions; 18, parameters; 19, block; 20, function_name:_do_work; 21, parameters; 22, block; 23, identifier:_do_work; 24, identifier:region_w_bams; 25, expression_statement; 26, expression_statement; 27, return_statement; 28, identifier:data; 29, expression_statement; 30, for_statement; 31, identifier:data; 32, if_statement; 33, assignment; 34, assignment; 35, binary_operator:end - start; 36, comment:"""Ensure BAMs aligned with input regions, either global or individual.
"""; 37, pattern_list; 38, call; 39, block; 40, comparison_operator:"region" in data; 41, block; 42, else_clause; 43, pattern_list; 44, identifier:region_w_bams; 45, pattern_list; 46, identifier:region; 47, identifier:end; 48, identifier:start; 49, identifier:i; 50, identifier:region; 51, identifier:enumerate; 52, argument_list; 53, expression_statement; 54, for_statement; 55, for_statement; 56, expression_statement; 57, string:"region"; 58, identifier:data; 59, expression_statement; 60, expression_statement; 61, expression_statement; 62, assert_statement; 63, expression_statement; 64, for_statement; 65, return_statement; 66, block; 67, identifier:region; 68, identifier:_; 69, identifier:_; 70, identifier:start; 71, identifier:end; 72, subscript; 73, assignment; 74, identifier:xs; 75, subscript; 76, block; 77, identifier:work_bam; 78, identifier:work_bams; 79, block; 80, yield; 81, assignment; 82, assignment; 83, assignment; 84, call; 85, assignment; 86, pattern_list; 87, call; 88, block; 89, expression_list; 90, return_statement; 91, identifier:data; 92, string:"region"; 93, identifier:work_bams; 94, list; 95, identifier:data; 96, string:"region_bams"; 97, if_statement; 98, assert_statement; 99, expression_list; 100, identifier:name; 101, conditional_expression:data["group"][0] if "group" in data else data["description"]; 102, identifier:out_dir; 103, call; 104, identifier:out_file; 105, call; 106, identifier:isinstance; 107, argument_list; 108, identifier:out_parts; 109, list; 110, identifier:r; 111, identifier:work_bams; 112, identifier:sorted; 113, argument_list; 114, expression_statement; 115, expression_statement; 116, expression_statement; 117, identifier:out_file; 118, identifier:out_parts; 119, expression_list; 120, comparison_operator:len(xs) == 1; 121, block; 122, else_clause; 123, call; 124, identifier:work_bam; 125, identifier:region; 126, identifier:work_bams; 127, subscript; 128, comparison_operator:"group" in data; 129, subscript; 130, attribute; 131, argument_list; 132, attribute; 133, argument_list; 134, subscript; 135, tuple; 136, call; 137, keyword_argument; 138, keyword_argument; 139, assignment; 140, assignment; 141, call; 142, None; 143, list; 144, call; 145, integer:1; 146, expression_statement; 147, block; 148, attribute; 149, argument_list; 150, subscript; 151, integer:0; 152, string:"group"; 153, identifier:data; 154, identifier:data; 155, string:"description"; 156, attribute; 157, identifier:join; 158, subscript; 159, call; 160, attribute; 161, identifier:join; 162, identifier:out_dir; 163, binary_operator:"%s%s" % (name, ext); 164, identifier:data; 165, string:"region"; 166, identifier:list; 167, identifier:tuple; 168, identifier:_assign_bams_to_regions; 169, argument_list; 170, identifier:key; 171, identifier:_sort_by_size; 172, identifier:reverse; 173, True; 174, identifier:out_region_dir; 175, call; 176, identifier:out_region_file; 177, call; 178, attribute; 179, argument_list; 180, identifier:len; 181, argument_list; 182, call; 183, expression_statement; 184, attribute; 185, identifier:exists; 186, identifier:work_bam; 187, identifier:data; 188, string:"group"; 189, identifier:os; 190, identifier:path; 191, subscript; 192, string:"work"; 193, identifier:dir_ext_fn; 194, argument_list; 195, identifier:os; 196, identifier:path; 197, string:"%s%s"; 198, tuple; 199, identifier:data; 200, attribute; 201, argument_list; 202, attribute; 203, argument_list; 204, identifier:out_parts; 205, identifier:append; 206, tuple; 207, identifier:xs; 208, attribute; 209, argument_list; 210, call; 211, identifier:os; 212, identifier:path; 213, identifier:data; 214, string:"dirs"; 215, identifier:data; 216, identifier:name; 217, identifier:ext; 218, attribute; 219, identifier:join; 220, identifier:out_dir; 221, subscript; 222, attribute; 223, identifier:join; 224, identifier:out_region_dir; 225, binary_operator:"%s-%s%s" % (name, pregion.to_safestr(r), ext); 226, identifier:r; 227, identifier:work_bams; 228, identifier:out_region_file; 229, identifier:work_bams; 230, identifier:append; 231, subscript; 232, attribute; 233, argument_list; 234, identifier:os; 235, identifier:path; 236, identifier:r; 237, integer:0; 238, identifier:os; 239, identifier:path; 240, string:"%s-%s%s"; 241, tuple; 242, identifier:xs; 243, integer:0; 244, identifier:work_bams; 245, identifier:append; 246, subscript; 247, identifier:name; 248, call; 249, identifier:ext; 250, identifier:xs; 251, identifier:i; 252, attribute; 253, argument_list; 254, identifier:pregion; 255, identifier:to_safestr; 256, identifier:r | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 8, 13; 9, 14; 9, 15; 9, 16; 10, 17; 10, 18; 10, 19; 11, 20; 11, 21; 11, 22; 12, 23; 15, 24; 16, 25; 16, 26; 16, 27; 18, 28; 19, 29; 19, 30; 21, 31; 22, 32; 25, 33; 26, 34; 27, 35; 29, 36; 30, 37; 30, 38; 30, 39; 32, 40; 32, 41; 32, 42; 33, 43; 33, 44; 34, 45; 34, 46; 35, 47; 35, 48; 37, 49; 37, 50; 38, 51; 38, 52; 39, 53; 39, 54; 39, 55; 39, 56; 40, 57; 40, 58; 41, 59; 41, 60; 41, 61; 41, 62; 41, 63; 41, 64; 41, 65; 42, 66; 43, 67; 43, 68; 45, 69; 45, 70; 45, 71; 52, 72; 53, 73; 54, 74; 54, 75; 54, 76; 55, 77; 55, 78; 55, 79; 56, 80; 59, 81; 60, 82; 61, 83; 62, 84; 63, 85; 64, 86; 64, 87; 64, 88; 65, 89; 66, 90; 72, 91; 72, 92; 73, 93; 73, 94; 75, 95; 75, 96; 76, 97; 79, 98; 80, 99; 81, 100; 81, 101; 82, 102; 82, 103; 83, 104; 83, 105; 84, 106; 84, 107; 85, 108; 85, 109; 86, 110; 86, 111; 87, 112; 87, 113; 88, 114; 88, 115; 88, 116; 89, 117; 89, 118; 90, 119; 97, 120; 97, 121; 97, 122; 98, 123; 98, 124; 99, 125; 99, 126; 101, 127; 101, 128; 101, 129; 103, 130; 103, 131; 105, 132; 105, 133; 107, 134; 107, 135; 113, 136; 113, 137; 113, 138; 114, 139; 115, 140; 116, 141; 119, 142; 119, 143; 120, 144; 120, 145; 121, 146; 122, 147; 123, 148; 123, 149; 127, 150; 127, 151; 128, 152; 128, 153; 129, 154; 129, 155; 130, 156; 130, 157; 131, 158; 131, 159; 132, 160; 132, 161; 133, 162; 133, 163; 134, 164; 134, 165; 135, 166; 135, 167; 136, 168; 136, 169; 137, 170; 137, 171; 138, 172; 138, 173; 139, 174; 139, 175; 140, 176; 140, 177; 141, 178; 141, 179; 144, 180; 144, 181; 146, 182; 147, 183; 148, 184; 148, 185; 149, 186; 150, 187; 150, 188; 156, 189; 156, 190; 158, 191; 158, 192; 159, 193; 159, 194; 160, 195; 160, 196; 163, 197; 163, 198; 169, 199; 175, 200; 175, 201; 177, 202; 177, 203; 178, 204; 178, 205; 179, 206; 181, 207; 182, 208; 182, 209; 183, 210; 184, 211; 184, 212; 191, 213; 191, 214; 194, 215; 198, 216; 198, 217; 200, 218; 200, 219; 201, 220; 201, 221; 202, 222; 202, 223; 203, 224; 203, 225; 206, 226; 206, 227; 206, 228; 208, 229; 208, 230; 209, 231; 210, 232; 210, 233; 218, 234; 218, 235; 221, 236; 221, 237; 222, 238; 222, 239; 225, 240; 225, 241; 231, 242; 231, 243; 232, 244; 232, 245; 233, 246; 241, 247; 241, 248; 241, 249; 246, 250; 246, 251; 248, 252; 248, 253; 252, 254; 252, 255; 253, 256 | def _split_by_ready_regions(ext, file_key, dir_ext_fn):
"""Organize splits based on regions generated by parallel_prep_region.
Sort splits so largest regions analyzed first, avoiding potentially lagging runs
at end.
"""
def _sort_by_size(region_w_bams):
region, _ = region_w_bams
_, start, end = region
return end - start
def _assign_bams_to_regions(data):
"""Ensure BAMs aligned with input regions, either global or individual.
"""
for i, region in enumerate(data["region"]):
work_bams = []
for xs in data["region_bams"]:
if len(xs) == 1:
work_bams.append(xs[0])
else:
work_bams.append(xs[i])
for work_bam in work_bams:
assert os.path.exists(work_bam), work_bam
yield region, work_bams
def _do_work(data):
if "region" in data:
name = data["group"][0] if "group" in data else data["description"]
out_dir = os.path.join(data["dirs"]["work"], dir_ext_fn(data))
out_file = os.path.join(out_dir, "%s%s" % (name, ext))
assert isinstance(data["region"], (list, tuple))
out_parts = []
for r, work_bams in sorted(_assign_bams_to_regions(data), key=_sort_by_size, reverse=True):
out_region_dir = os.path.join(out_dir, r[0])
out_region_file = os.path.join(out_region_dir,
"%s-%s%s" % (name, pregion.to_safestr(r), ext))
out_parts.append((r, work_bams, out_region_file))
return out_file, out_parts
else:
return None, []
return _do_work |
0, module; 1, function_definition; 2, function_name:_combine_variants; 3, parameters; 4, block; 5, identifier:in_vcfs; 6, identifier:out_file; 7, identifier:ref_file; 8, identifier:config; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, with_statement; 13, return_statement; 14, comment:"""Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the expected order.
"""; 15, call; 16, assignment; 17, with_clause; 18, block; 19, identifier:out_file; 20, attribute; 21, argument_list; 22, identifier:wrote_header; 23, False; 24, with_item; 25, for_statement; 26, if_statement; 27, identifier:in_vcfs; 28, identifier:sort; 29, as_pattern; 30, identifier:in_vcf; 31, generator_expression; 32, block; 33, not_operator; 34, block; 35, call; 36, as_pattern_target; 37, subscript; 38, for_in_clause; 39, with_statement; 40, identifier:wrote_header; 41, expression_statement; 42, identifier:open; 43, argument_list; 44, identifier:out_handle; 45, identifier:x; 46, unary_operator; 47, identifier:x; 48, identifier:in_vcfs; 49, with_clause; 50, block; 51, call; 52, identifier:out_file; 53, string:"w"; 54, integer:1; 55, with_item; 56, expression_statement; 57, if_statement; 58, for_statement; 59, attribute; 60, argument_list; 61, as_pattern; 62, assignment; 63, not_operator; 64, block; 65, identifier:line; 66, identifier:in_handle; 67, block; 68, identifier:out_handle; 69, identifier:write; 70, call; 71, call; 72, as_pattern_target; 73, identifier:header; 74, call; 75, call; 76, raise_statement; 77, if_statement; 78, expression_statement; 79, attribute; 80, argument_list; 81, identifier:open; 82, argument_list; 83, identifier:in_handle; 84, identifier:list; 85, argument_list; 86, attribute; 87, argument_list; 88, call; 89, not_operator; 90, block; 91, call; 92, string:""; 93, identifier:join; 94, identifier:header; 95, identifier:in_vcf; 96, call; 97, subscript; 98, identifier:startswith; 99, string:"##fileformat=VCFv4"; 100, identifier:ValueError; 101, argument_list; 102, identifier:wrote_header; 103, expression_statement; 104, expression_statement; 105, attribute; 106, argument_list; 107, attribute; 108, argument_list; 109, identifier:header; 110, integer:0; 111, binary_operator:"Unexpected VCF file: %s" % in_vcf; 112, assignment; 113, call; 114, identifier:out_handle; 115, identifier:write; 116, identifier:line; 117, identifier:itertools; 118, identifier:takewhile; 119, lambda; 120, identifier:in_handle; 121, string:"Unexpected VCF file: %s"; 122, identifier:in_vcf; 123, identifier:wrote_header; 124, True; 125, attribute; 126, argument_list; 127, lambda_parameters; 128, call; 129, identifier:out_handle; 130, identifier:write; 131, call; 132, identifier:x; 133, attribute; 134, argument_list; 135, attribute; 136, argument_list; 137, identifier:x; 138, identifier:startswith; 139, string:"#"; 140, string:""; 141, identifier:join; 142, identifier:header | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 9, 14; 10, 15; 11, 16; 12, 17; 12, 18; 13, 19; 15, 20; 15, 21; 16, 22; 16, 23; 17, 24; 18, 25; 18, 26; 20, 27; 20, 28; 24, 29; 25, 30; 25, 31; 25, 32; 26, 33; 26, 34; 29, 35; 29, 36; 31, 37; 31, 38; 32, 39; 33, 40; 34, 41; 35, 42; 35, 43; 36, 44; 37, 45; 37, 46; 38, 47; 38, 48; 39, 49; 39, 50; 41, 51; 43, 52; 43, 53; 46, 54; 49, 55; 50, 56; 50, 57; 50, 58; 51, 59; 51, 60; 55, 61; 56, 62; 57, 63; 57, 64; 58, 65; 58, 66; 58, 67; 59, 68; 59, 69; 60, 70; 61, 71; 61, 72; 62, 73; 62, 74; 63, 75; 64, 76; 67, 77; 67, 78; 70, 79; 70, 80; 71, 81; 71, 82; 72, 83; 74, 84; 74, 85; 75, 86; 75, 87; 76, 88; 77, 89; 77, 90; 78, 91; 79, 92; 79, 93; 80, 94; 82, 95; 85, 96; 86, 97; 86, 98; 87, 99; 88, 100; 88, 101; 89, 102; 90, 103; 90, 104; 91, 105; 91, 106; 96, 107; 96, 108; 97, 109; 97, 110; 101, 111; 103, 112; 104, 113; 105, 114; 105, 115; 106, 116; 107, 117; 107, 118; 108, 119; 108, 120; 111, 121; 111, 122; 112, 123; 112, 124; 113, 125; 113, 126; 119, 127; 119, 128; 125, 129; 125, 130; 126, 131; 127, 132; 128, 133; 128, 134; 131, 135; 131, 136; 133, 137; 133, 138; 134, 139; 135, 140; 135, 141; 136, 142 | def _combine_variants(in_vcfs, out_file, ref_file, config):
"""Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the expected order.
"""
in_vcfs.sort()
wrote_header = False
with open(out_file, "w") as out_handle:
for in_vcf in (x[-1] for x in in_vcfs):
with open(in_vcf) as in_handle:
header = list(itertools.takewhile(lambda x: x.startswith("#"),
in_handle))
if not header[0].startswith("##fileformat=VCFv4"):
raise ValueError("Unexpected VCF file: %s" % in_vcf)
for line in in_handle:
if not wrote_header:
wrote_header = True
out_handle.write("".join(header))
out_handle.write(line)
if not wrote_header:
out_handle.write("".join(header))
return out_file |
0, module; 1, function_definition; 2, function_name:picard_sort; 3, parameters; 4, block; 5, identifier:picard; 6, identifier:align_bam; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, if_statement; 15, return_statement; 16, identifier:sort_order; 17, string:"coordinate"; 18, identifier:out_file; 19, None; 20, identifier:compression_level; 21, None; 22, identifier:pipe; 23, False; 24, comment:"""Sort a BAM file by coordinates.
"""; 25, assignment; 26, comparison_operator:out_file is None; 27, block; 28, not_operator; 29, block; 30, identifier:out_file; 31, pattern_list; 32, call; 33, identifier:out_file; 34, None; 35, expression_statement; 36, call; 37, with_statement; 38, identifier:base; 39, identifier:ext; 40, attribute; 41, argument_list; 42, assignment; 43, identifier:file_exists; 44, argument_list; 45, with_clause; 46, block; 47, attribute; 48, identifier:splitext; 49, identifier:align_bam; 50, identifier:out_file; 51, binary_operator:"%s-sort%s" % (base, ext); 52, identifier:out_file; 53, with_item; 54, with_statement; 55, identifier:os; 56, identifier:path; 57, string:"%s-sort%s"; 58, tuple; 59, as_pattern; 60, with_clause; 61, block; 62, identifier:base; 63, identifier:ext; 64, call; 65, as_pattern_target; 66, with_item; 67, expression_statement; 68, if_statement; 69, expression_statement; 70, identifier:tx_tmpdir; 71, argument_list; 72, identifier:tmp_dir; 73, as_pattern; 74, assignment; 75, identifier:compression_level; 76, block; 77, call; 78, attribute; 79, call; 80, as_pattern_target; 81, identifier:opts; 82, list; 83, expression_statement; 84, attribute; 85, argument_list; 86, identifier:picard; 87, identifier:_config; 88, identifier:file_transaction; 89, argument_list; 90, identifier:tx_out_file; 91, tuple; 92, tuple; 93, tuple; 94, tuple; 95, call; 96, identifier:picard; 97, identifier:run; 98, string:"SortSam"; 99, identifier:opts; 100, keyword_argument; 101, attribute; 102, identifier:out_file; 103, string:"INPUT"; 104, identifier:align_bam; 105, string:"OUTPUT"; 106, conditional_expression:out_file if pipe else tx_out_file; 107, string:"TMP_DIR"; 108, identifier:tmp_dir; 109, string:"SORT_ORDER"; 110, identifier:sort_order; 111, attribute; 112, argument_list; 113, identifier:pipe; 114, identifier:pipe; 115, identifier:picard; 116, identifier:_config; 117, identifier:out_file; 118, identifier:pipe; 119, identifier:tx_out_file; 120, identifier:opts; 121, identifier:append; 122, tuple; 123, string:"COMPRESSION_LEVEL"; 124, identifier:compression_level | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 7, 16; 7, 17; 8, 18; 8, 19; 9, 20; 9, 21; 10, 22; 10, 23; 11, 24; 12, 25; 13, 26; 13, 27; 14, 28; 14, 29; 15, 30; 25, 31; 25, 32; 26, 33; 26, 34; 27, 35; 28, 36; 29, 37; 31, 38; 31, 39; 32, 40; 32, 41; 35, 42; 36, 43; 36, 44; 37, 45; 37, 46; 40, 47; 40, 48; 41, 49; 42, 50; 42, 51; 44, 52; 45, 53; 46, 54; 47, 55; 47, 56; 51, 57; 51, 58; 53, 59; 54, 60; 54, 61; 58, 62; 58, 63; 59, 64; 59, 65; 60, 66; 61, 67; 61, 68; 61, 69; 64, 70; 64, 71; 65, 72; 66, 73; 67, 74; 68, 75; 68, 76; 69, 77; 71, 78; 73, 79; 73, 80; 74, 81; 74, 82; 76, 83; 77, 84; 77, 85; 78, 86; 78, 87; 79, 88; 79, 89; 80, 90; 82, 91; 82, 92; 82, 93; 82, 94; 83, 95; 84, 96; 84, 97; 85, 98; 85, 99; 85, 100; 89, 101; 89, 102; 91, 103; 91, 104; 92, 105; 92, 106; 93, 107; 93, 108; 94, 109; 94, 110; 95, 111; 95, 112; 100, 113; 100, 114; 101, 115; 101, 116; 106, 117; 106, 118; 106, 119; 111, 120; 111, 121; 112, 122; 122, 123; 122, 124 | def picard_sort(picard, align_bam, sort_order="coordinate",
out_file=None, compression_level=None, pipe=False):
"""Sort a BAM file by coordinates.
"""
base, ext = os.path.splitext(align_bam)
if out_file is None:
out_file = "%s-sort%s" % (base, ext)
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", align_bam),
("OUTPUT", out_file if pipe else tx_out_file),
("TMP_DIR", tmp_dir),
("SORT_ORDER", sort_order)]
if compression_level:
opts.append(("COMPRESSION_LEVEL", compression_level))
picard.run("SortSam", opts, pipe=pipe)
return out_file |
0, module; 1, function_definition; 2, function_name:picard_fix_rgs; 3, parameters; 4, block; 5, identifier:picard; 6, identifier:in_bam; 7, identifier:names; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, return_statement; 12, comment:"""Add read group information to BAM files and coordinate sort.
"""; 13, assignment; 14, not_operator; 15, block; 16, identifier:out_file; 17, identifier:out_file; 18, binary_operator:"%s-fixrgs.bam" % os.path.splitext(in_bam)[0]; 19, call; 20, with_statement; 21, string:"%s-fixrgs.bam"; 22, subscript; 23, identifier:file_exists; 24, argument_list; 25, with_clause; 26, block; 27, call; 28, integer:0; 29, identifier:out_file; 30, with_item; 31, with_statement; 32, attribute; 33, argument_list; 34, as_pattern; 35, with_clause; 36, block; 37, attribute; 38, identifier:splitext; 39, identifier:in_bam; 40, call; 41, as_pattern_target; 42, with_item; 43, expression_statement; 44, expression_statement; 45, identifier:os; 46, identifier:path; 47, identifier:tx_tmpdir; 48, argument_list; 49, identifier:tmp_dir; 50, as_pattern; 51, assignment; 52, call; 53, attribute; 54, call; 55, as_pattern_target; 56, identifier:opts; 57, list; 58, attribute; 59, argument_list; 60, identifier:picard; 61, identifier:_config; 62, identifier:file_transaction; 63, argument_list; 64, identifier:tx_out_file; 65, tuple; 66, tuple; 67, tuple; 68, tuple; 69, tuple; 70, tuple; 71, tuple; 72, tuple; 73, tuple; 74, identifier:picard; 75, identifier:run; 76, string:"AddOrReplaceReadGroups"; 77, identifier:opts; 78, attribute; 79, identifier:out_file; 80, string:"INPUT"; 81, identifier:in_bam; 82, string:"OUTPUT"; 83, identifier:tx_out_file; 84, string:"SORT_ORDER"; 85, string:"coordinate"; 86, string:"RGID"; 87, subscript; 88, string:"RGLB"; 89, call; 90, string:"RGPL"; 91, subscript; 92, string:"RGPU"; 93, subscript; 94, string:"RGSM"; 95, subscript; 96, string:"TMP_DIR"; 97, identifier:tmp_dir; 98, identifier:picard; 99, identifier:_config; 100, identifier:names; 101, string:"rg"; 102, attribute; 103, argument_list; 104, identifier:names; 105, string:"pl"; 106, identifier:names; 107, string:"pu"; 108, identifier:names; 109, string:"sample"; 110, identifier:names; 111, identifier:get; 112, string:"lb"; 113, string:"unknown" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 8, 12; 9, 13; 10, 14; 10, 15; 11, 16; 13, 17; 13, 18; 14, 19; 15, 20; 18, 21; 18, 22; 19, 23; 19, 24; 20, 25; 20, 26; 22, 27; 22, 28; 24, 29; 25, 30; 26, 31; 27, 32; 27, 33; 30, 34; 31, 35; 31, 36; 32, 37; 32, 38; 33, 39; 34, 40; 34, 41; 35, 42; 36, 43; 36, 44; 37, 45; 37, 46; 40, 47; 40, 48; 41, 49; 42, 50; 43, 51; 44, 52; 48, 53; 50, 54; 50, 55; 51, 56; 51, 57; 52, 58; 52, 59; 53, 60; 53, 61; 54, 62; 54, 63; 55, 64; 57, 65; 57, 66; 57, 67; 57, 68; 57, 69; 57, 70; 57, 71; 57, 72; 57, 73; 58, 74; 58, 75; 59, 76; 59, 77; 63, 78; 63, 79; 65, 80; 65, 81; 66, 82; 66, 83; 67, 84; 67, 85; 68, 86; 68, 87; 69, 88; 69, 89; 70, 90; 70, 91; 71, 92; 71, 93; 72, 94; 72, 95; 73, 96; 73, 97; 78, 98; 78, 99; 87, 100; 87, 101; 89, 102; 89, 103; 91, 104; 91, 105; 93, 106; 93, 107; 95, 108; 95, 109; 102, 110; 102, 111; 103, 112; 103, 113 | def picard_fix_rgs(picard, in_bam, names):
"""Add read group information to BAM files and coordinate sort.
"""
out_file = "%s-fixrgs.bam" % os.path.splitext(in_bam)[0]
if not file_exists(out_file):
with tx_tmpdir(picard._config) as tmp_dir:
with file_transaction(picard._config, out_file) as tx_out_file:
opts = [("INPUT", in_bam),
("OUTPUT", tx_out_file),
("SORT_ORDER", "coordinate"),
("RGID", names["rg"]),
("RGLB", names.get("lb", "unknown")),
("RGPL", names["pl"]),
("RGPU", names["pu"]),
("RGSM", names["sample"]),
("TMP_DIR", tmp_dir)]
picard.run("AddOrReplaceReadGroups", opts)
return out_file |
0, module; 1, function_definition; 2, function_name:_enforce_max_region_size; 3, parameters; 4, block; 5, identifier:in_file; 6, identifier:data; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, function_definition; 11, expression_statement; 12, if_statement; 13, return_statement; 14, comment:"""Ensure we don't have any chunks in the region greater than 20kb.
VarDict memory usage depends on size of individual windows in the input
file. This breaks regions into 20kb chunks with 250bp overlaps. 20kb gives
~1Gb/core memory usage and the overlaps avoid missing indels spanning a
gap. Downstream VarDict merging sorts out any variants across windows.
https://github.com/AstraZeneca-NGS/VarDictJava/issues/64
"""; 15, assignment; 16, assignment; 17, function_name:_has_larger_regions; 18, parameters; 19, block; 20, assignment; 21, not_operator; 22, block; 23, identifier:out_file; 24, identifier:max_size; 25, integer:20000; 26, identifier:overlap_size; 27, integer:250; 28, identifier:f; 29, return_statement; 30, identifier:out_file; 31, binary_operator:"%s-regionlimit%s" % utils.splitext_plus(in_file); 32, call; 33, if_statement; 34, call; 35, string:"%s-regionlimit%s"; 36, call; 37, attribute; 38, argument_list; 39, call; 40, block; 41, else_clause; 42, identifier:any; 43, generator_expression; 44, attribute; 45, argument_list; 46, identifier:utils; 47, identifier:file_exists; 48, identifier:out_file; 49, identifier:_has_larger_regions; 50, argument_list; 51, with_statement; 52, block; 53, comparison_operator:r.stop - r.start > max_size; 54, for_in_clause; 55, identifier:utils; 56, identifier:splitext_plus; 57, identifier:in_file; 58, identifier:in_file; 59, with_clause; 60, block; 61, expression_statement; 62, binary_operator:r.stop - r.start; 63, identifier:max_size; 64, identifier:r; 65, call; 66, with_item; 67, expression_statement; 68, call; 69, attribute; 70, attribute; 71, attribute; 72, argument_list; 73, as_pattern; 74, call; 75, attribute; 76, argument_list; 77, identifier:r; 78, identifier:stop; 79, identifier:r; 80, identifier:start; 81, identifier:pybedtools; 82, identifier:BedTool; 83, identifier:f; 84, call; 85, as_pattern_target; 86, attribute; 87, argument_list; 88, identifier:utils; 89, identifier:symlink_plus; 90, identifier:in_file; 91, identifier:out_file; 92, identifier:file_transaction; 93, argument_list; 94, identifier:tx_out_file; 95, call; 96, identifier:saveas; 97, identifier:tx_out_file; 98, identifier:data; 99, identifier:out_file; 100, attribute; 101, argument_list; 102, call; 103, identifier:window_maker; 104, keyword_argument; 105, keyword_argument; 106, keyword_argument; 107, attribute; 108, argument_list; 109, identifier:w; 110, identifier:max_size; 111, identifier:s; 112, binary_operator:max_size - overlap_size; 113, identifier:b; 114, call; 115, identifier:pybedtools; 116, identifier:BedTool; 117, identifier:max_size; 118, identifier:overlap_size; 119, attribute; 120, argument_list; 121, identifier:pybedtools; 122, identifier:BedTool; 123, identifier:in_file | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 7, 14; 8, 15; 9, 16; 10, 17; 10, 18; 10, 19; 11, 20; 12, 21; 12, 22; 13, 23; 15, 24; 15, 25; 16, 26; 16, 27; 18, 28; 19, 29; 20, 30; 20, 31; 21, 32; 22, 33; 29, 34; 31, 35; 31, 36; 32, 37; 32, 38; 33, 39; 33, 40; 33, 41; 34, 42; 34, 43; 36, 44; 36, 45; 37, 46; 37, 47; 38, 48; 39, 49; 39, 50; 40, 51; 41, 52; 43, 53; 43, 54; 44, 55; 44, 56; 45, 57; 50, 58; 51, 59; 51, 60; 52, 61; 53, 62; 53, 63; 54, 64; 54, 65; 59, 66; 60, 67; 61, 68; 62, 69; 62, 70; 65, 71; 65, 72; 66, 73; 67, 74; 68, 75; 68, 76; 69, 77; 69, 78; 70, 79; 70, 80; 71, 81; 71, 82; 72, 83; 73, 84; 73, 85; 74, 86; 74, 87; 75, 88; 75, 89; 76, 90; 76, 91; 84, 92; 84, 93; 85, 94; 86, 95; 86, 96; 87, 97; 93, 98; 93, 99; 95, 100; 95, 101; 100, 102; 100, 103; 101, 104; 101, 105; 101, 106; 102, 107; 102, 108; 104, 109; 104, 110; 105, 111; 105, 112; 106, 113; 106, 114; 107, 115; 107, 116; 112, 117; 112, 118; 114, 119; 114, 120; 119, 121; 119, 122; 120, 123 | def _enforce_max_region_size(in_file, data):
"""Ensure we don't have any chunks in the region greater than 20kb.
VarDict memory usage depends on size of individual windows in the input
file. This breaks regions into 20kb chunks with 250bp overlaps. 20kb gives
~1Gb/core memory usage and the overlaps avoid missing indels spanning a
gap. Downstream VarDict merging sorts out any variants across windows.
https://github.com/AstraZeneca-NGS/VarDictJava/issues/64
"""
max_size = 20000
overlap_size = 250
def _has_larger_regions(f):
return any(r.stop - r.start > max_size for r in pybedtools.BedTool(f))
out_file = "%s-regionlimit%s" % utils.splitext_plus(in_file)
if not utils.file_exists(out_file):
if _has_larger_regions(in_file):
with file_transaction(data, out_file) as tx_out_file:
pybedtools.BedTool().window_maker(w=max_size,
s=max_size - overlap_size,
b=pybedtools.BedTool(in_file)).saveas(tx_out_file)
else:
utils.symlink_plus(in_file, out_file)
return out_file |
0, module; 1, function_definition; 2, function_name:_prep_vrn_file; 3, parameters; 4, block; 5, identifier:in_file; 6, identifier:vcaller; 7, identifier:work_dir; 8, identifier:somatic_info; 9, identifier:ignore_file; 10, identifier:config; 11, expression_statement; 12, if_statement; 13, expression_statement; 14, if_statement; 15, return_statement; 16, comment:"""Create a variant file to feed into the PhyloWGS prep script, limiting records.
Sorts by depth, adding top covered samples up to the sample_size supported
by PhyloWGS. The logic is that the higher depth samples will have better
resolution for frequency differences. More complex implementations could try
to subset based on a distribution of frequencies to best sample the potential
heterogeneity.
Handles MuTect and VarDict as inputs to PhyloWGS.
Fixes chromosome naming to use non chr-prefixed contigs, to match _prep_cnv_file.
"""; 17, call; 18, block; 19, elif_clause; 20, else_clause; 21, assignment; 22, not_operator; 23, block; 24, expression_list; 25, attribute; 26, argument_list; 27, expression_statement; 28, comparison_operator:vcaller == "mutect"; 29, block; 30, block; 31, identifier:out_file; 32, call; 33, call; 34, expression_statement; 35, with_statement; 36, identifier:variant_type; 37, identifier:out_file; 38, identifier:vcaller; 39, identifier:startswith; 40, string:"vardict"; 41, assignment; 42, identifier:vcaller; 43, string:"mutect"; 44, expression_statement; 45, raise_statement; 46, attribute; 47, argument_list; 48, attribute; 49, argument_list; 50, assignment; 51, with_clause; 52, block; 53, identifier:variant_type; 54, string:"vardict"; 55, assignment; 56, call; 57, attribute; 58, identifier:join; 59, identifier:work_dir; 60, binary_operator:"%s-%s-prep.vcf" % (utils.splitext_plus(os.path.basename(in_file))[0],
vcaller); 61, identifier:utils; 62, identifier:file_uptodate; 63, identifier:out_file; 64, identifier:in_file; 65, identifier:check_fn; 66, call; 67, with_item; 68, expression_statement; 69, comment:# Filter inputs; 70, with_statement; 71, with_statement; 72, comment:# Fix potential chromosome issues; 73, with_statement; 74, identifier:variant_type; 75, string:"mutect-smchet"; 76, identifier:ValueError; 77, argument_list; 78, identifier:os; 79, identifier:path; 80, string:"%s-%s-prep.vcf"; 81, tuple; 82, identifier:_min_sample_pass; 83, argument_list; 84, as_pattern; 85, assignment; 86, with_clause; 87, block; 88, with_clause; 89, block; 90, with_clause; 91, block; 92, binary_operator:"Unexpected variant caller for PhyloWGS prep: %s" % vcaller; 93, subscript; 94, identifier:vcaller; 95, identifier:ignore_file; 96, call; 97, as_pattern_target; 98, identifier:tx_out_file_raw; 99, binary_operator:"%s-raw%s" % utils.splitext_plus(tx_out_file); 100, with_item; 101, expression_statement; 102, expression_statement; 103, expression_statement; 104, with_item; 105, with_statement; 106, with_item; 107, with_statement; 108, string:"Unexpected variant caller for PhyloWGS prep: %s"; 109, identifier:vcaller; 110, call; 111, integer:0; 112, identifier:file_transaction; 113, argument_list; 114, identifier:tx_out_file; 115, string:"%s-raw%s"; 116, call; 117, as_pattern; 118, assignment; 119, call; 120, assignment; 121, as_pattern; 122, with_clause; 123, block; 124, as_pattern; 125, with_clause; 126, block; 127, attribute; 128, argument_list; 129, attribute; 130, identifier:out_file; 131, attribute; 132, argument_list; 133, call; 134, as_pattern_target; 135, identifier:depths; 136, list_comprehension; 137, attribute; 138, argument_list; 139, identifier:depth_thresh; 140, conditional_expression:depths[:config["sample_size"]][-1] if depths else 0; 141, call; 142, as_pattern_target; 143, with_item; 144, for_statement; 145, call; 146, as_pattern_target; 147, with_item; 148, for_statement; 149, identifier:utils; 150, identifier:splitext_plus; 151, call; 152, identifier:somatic_info; 153, identifier:tumor_data; 154, identifier:utils; 155, identifier:splitext_plus; 156, identifier:tx_out_file; 157, identifier:VariantFile; 158, argument_list; 159, identifier:bcf_in; 160, call; 161, for_in_clause; 162, identifier:depths; 163, identifier:sort; 164, keyword_argument; 165, subscript; 166, identifier:depths; 167, integer:0; 168, identifier:VariantFile; 169, argument_list; 170, identifier:bcf_in; 171, as_pattern; 172, identifier:rec; 173, identifier:bcf_in; 174, block; 175, identifier:open; 176, argument_list; 177, identifier:in_handle; 178, as_pattern; 179, identifier:line; 180, identifier:in_handle; 181, block; 182, attribute; 183, argument_list; 184, identifier:in_file; 185, identifier:_sample_depth; 186, argument_list; 187, identifier:rec; 188, call; 189, identifier:reverse; 190, True; 191, subscript; 192, unary_operator; 193, identifier:in_file; 194, call; 195, as_pattern_target; 196, if_statement; 197, identifier:tx_out_file_raw; 198, call; 199, as_pattern_target; 200, if_statement; 201, expression_statement; 202, attribute; 203, identifier:basename; 204, identifier:in_file; 205, identifier:rec; 206, attribute; 207, identifier:filter; 208, argument_list; 209, identifier:depths; 210, slice; 211, integer:1; 212, identifier:VariantFile; 213, argument_list; 214, identifier:bcf_out; 215, parenthesized_expression; 216, block; 217, identifier:open; 218, argument_list; 219, identifier:out_handle; 220, not_operator; 221, block; 222, call; 223, identifier:os; 224, identifier:path; 225, identifier:somatic_info; 226, identifier:tumor_name; 227, identifier:check_fn; 228, identifier:bcf_in; 229, subscript; 230, identifier:tx_out_file_raw; 231, string:"w"; 232, keyword_argument; 233, boolean_operator; 234, expression_statement; 235, identifier:tx_out_file; 236, string:"w"; 237, call; 238, expression_statement; 239, expression_statement; 240, expression_statement; 241, attribute; 242, argument_list; 243, identifier:config; 244, string:"sample_size"; 245, identifier:header; 246, attribute; 247, call; 248, parenthesized_expression; 249, call; 250, attribute; 251, argument_list; 252, assignment; 253, assignment; 254, assignment; 255, identifier:out_handle; 256, identifier:write; 257, identifier:line; 258, identifier:bcf_in; 259, identifier:header; 260, identifier:check_fn; 261, argument_list; 262, boolean_operator; 263, attribute; 264, argument_list; 265, identifier:line; 266, identifier:startswith; 267, string:"#"; 268, identifier:parts; 269, call; 270, subscript; 271, call; 272, identifier:line; 273, call; 274, identifier:rec; 275, comparison_operator:depth_thresh < 5; 276, comparison_operator:_sample_depth(rec, somatic_info.tumor_name) >= depth_thresh; 277, identifier:bcf_out; 278, identifier:write; 279, identifier:rec; 280, attribute; 281, argument_list; 282, identifier:parts; 283, integer:0; 284, identifier:_phylowgs_compatible_chroms; 285, argument_list; 286, attribute; 287, argument_list; 288, identifier:depth_thresh; 289, integer:5; 290, call; 291, identifier:depth_thresh; 292, identifier:line; 293, identifier:split; 294, string:"\t"; 295, subscript; 296, string:"\t"; 297, identifier:join; 298, identifier:parts; 299, identifier:_sample_depth; 300, argument_list; 301, identifier:parts; 302, integer:0; 303, identifier:rec; 304, attribute; 305, identifier:somatic_info; 306, identifier:tumor_name | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 11, 16; 12, 17; 12, 18; 12, 19; 12, 20; 13, 21; 14, 22; 14, 23; 15, 24; 17, 25; 17, 26; 18, 27; 19, 28; 19, 29; 20, 30; 21, 31; 21, 32; 22, 33; 23, 34; 23, 35; 24, 36; 24, 37; 25, 38; 25, 39; 26, 40; 27, 41; 28, 42; 28, 43; 29, 44; 30, 45; 32, 46; 32, 47; 33, 48; 33, 49; 34, 50; 35, 51; 35, 52; 41, 53; 41, 54; 44, 55; 45, 56; 46, 57; 46, 58; 47, 59; 47, 60; 48, 61; 48, 62; 49, 63; 49, 64; 50, 65; 50, 66; 51, 67; 52, 68; 52, 69; 52, 70; 52, 71; 52, 72; 52, 73; 55, 74; 55, 75; 56, 76; 56, 77; 57, 78; 57, 79; 60, 80; 60, 81; 66, 82; 66, 83; 67, 84; 68, 85; 70, 86; 70, 87; 71, 88; 71, 89; 73, 90; 73, 91; 77, 92; 81, 93; 81, 94; 83, 95; 84, 96; 84, 97; 85, 98; 85, 99; 86, 100; 87, 101; 87, 102; 87, 103; 88, 104; 89, 105; 90, 106; 91, 107; 92, 108; 92, 109; 93, 110; 93, 111; 96, 112; 96, 113; 97, 114; 99, 115; 99, 116; 100, 117; 101, 118; 102, 119; 103, 120; 104, 121; 105, 122; 105, 123; 106, 124; 107, 125; 107, 126; 110, 127; 110, 128; 113, 129; 113, 130; 116, 131; 116, 132; 117, 133; 117, 134; 118, 135; 118, 136; 119, 137; 119, 138; 120, 139; 120, 140; 121, 141; 121, 142; 122, 143; 123, 144; 124, 145; 124, 146; 125, 147; 126, 148; 127, 149; 127, 150; 128, 151; 129, 152; 129, 153; 131, 154; 131, 155; 132, 156; 133, 157; 133, 158; 134, 159; 136, 160; 136, 161; 137, 162; 137, 163; 138, 164; 140, 165; 140, 166; 140, 167; 141, 168; 141, 169; 142, 170; 143, 171; 144, 172; 144, 173; 144, 174; 145, 175; 145, 176; 146, 177; 147, 178; 148, 179; 148, 180; 148, 181; 151, 182; 151, 183; 158, 184; 160, 185; 160, 186; 161, 187; 161, 188; 164, 189; 164, 190; 165, 191; 165, 192; 169, 193; 171, 194; 171, 195; 174, 196; 176, 197; 178, 198; 178, 199; 181, 200; 181, 201; 182, 202; 182, 203; 183, 204; 186, 205; 186, 206; 188, 207; 188, 208; 191, 209; 191, 210; 192, 211; 194, 212; 194, 213; 195, 214; 196, 215; 196, 216; 198, 217; 198, 218; 199, 219; 200, 220; 200, 221; 201, 222; 202, 223; 202, 224; 206, 225; 206, 226; 208, 227; 208, 228; 210, 229; 213, 230; 213, 231; 213, 232; 215, 233; 216, 234; 218, 235; 218, 236; 220, 237; 221, 238; 221, 239; 221, 240; 222, 241; 222, 242; 229, 243; 229, 244; 232, 245; 232, 246; 233, 247; 233, 248; 234, 249; 237, 250; 237, 251; 238, 252; 239, 253; 240, 254; 241, 255; 241, 256; 242, 257; 246, 258; 246, 259; 247, 260; 247, 261; 248, 262; 249, 263; 249, 264; 250, 265; 250, 266; 251, 267; 252, 268; 252, 269; 253, 270; 253, 271; 254, 272; 254, 273; 261, 274; 262, 275; 262, 276; 263, 277; 263, 278; 264, 279; 269, 280; 269, 281; 270, 282; 270, 283; 271, 284; 271, 285; 273, 286; 273, 287; 275, 288; 275, 289; 276, 290; 276, 291; 280, 292; 280, 293; 281, 294; 285, 295; 286, 296; 286, 297; 287, 298; 290, 299; 290, 300; 295, 301; 295, 302; 300, 303; 300, 304; 304, 305; 304, 306 | def _prep_vrn_file(in_file, vcaller, work_dir, somatic_info, ignore_file, config):
"""Create a variant file to feed into the PhyloWGS prep script, limiting records.
Sorts by depth, adding top covered samples up to the sample_size supported
by PhyloWGS. The logic is that the higher depth samples will have better
resolution for frequency differences. More complex implementations could try
to subset based on a distribution of frequencies to best sample the potential
heterogeneity.
Handles MuTect and VarDict as inputs to PhyloWGS.
Fixes chromosome naming to use non chr-prefixed contigs, to match _prep_cnv_file.
"""
if vcaller.startswith("vardict"):
variant_type = "vardict"
elif vcaller == "mutect":
variant_type = "mutect-smchet"
else:
raise ValueError("Unexpected variant caller for PhyloWGS prep: %s" % vcaller)
out_file = os.path.join(work_dir, "%s-%s-prep.vcf" % (utils.splitext_plus(os.path.basename(in_file))[0],
vcaller))
if not utils.file_uptodate(out_file, in_file):
check_fn = _min_sample_pass(ignore_file)
with file_transaction(somatic_info.tumor_data, out_file) as tx_out_file:
tx_out_file_raw = "%s-raw%s" % utils.splitext_plus(tx_out_file)
# Filter inputs
with VariantFile(in_file) as bcf_in:
depths = [_sample_depth(rec, somatic_info.tumor_name) for rec in
filter(check_fn, bcf_in)]
depths.sort(reverse=True)
depth_thresh = depths[:config["sample_size"]][-1] if depths else 0
with VariantFile(in_file) as bcf_in:
with VariantFile(tx_out_file_raw, "w", header=bcf_in.header) as bcf_out:
for rec in bcf_in:
if (check_fn(rec) and
(depth_thresh < 5 or _sample_depth(rec, somatic_info.tumor_name) >= depth_thresh)):
bcf_out.write(rec)
# Fix potential chromosome issues
with open(tx_out_file_raw) as in_handle:
with open(tx_out_file, "w") as out_handle:
for line in in_handle:
if not line.startswith("#"):
parts = line.split("\t")
parts[0] = _phylowgs_compatible_chroms(parts[0])
line = "\t".join(parts)
out_handle.write(line)
return variant_type, out_file |
0, module; 1, function_definition; 2, function_name:concat; 3, parameters; 4, block; 5, identifier:bed_files; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, if_statement; 11, return_statement; 12, identifier:catted; 13, None; 14, comment:"""
recursively concat a set of BED files, returning a
sorted bedtools object of the result
"""; 15, assignment; 16, comparison_operator:len(bed_files) == 0; 17, block; 18, not_operator; 19, block; 20, else_clause; 21, call; 22, identifier:bed_files; 23, list_comprehension; 24, call; 25, integer:0; 26, if_statement; 27, identifier:catted; 28, expression_statement; 29, expression_statement; 30, block; 31, identifier:concat; 32, argument_list; 33, identifier:x; 34, for_in_clause; 35, if_clause; 36, identifier:len; 37, argument_list; 38, identifier:catted; 39, comment:# move to a .bed extension for downstream tools if not already; 40, block; 41, else_clause; 42, assignment; 43, assignment; 44, expression_statement; 45, identifier:bed_files; 46, identifier:catted; 47, identifier:x; 48, identifier:bed_files; 49, identifier:x; 50, identifier:bed_files; 51, expression_statement; 52, if_statement; 53, block; 54, identifier:bed_files; 55, call; 56, identifier:catted; 57, call; 58, assignment; 59, assignment; 60, not_operator; 61, block; 62, else_clause; 63, return_statement; 64, identifier:list; 65, argument_list; 66, attribute; 67, argument_list; 68, identifier:catted; 69, call; 70, identifier:sorted_bed; 71, call; 72, call; 73, return_statement; 74, block; 75, identifier:catted; 76, identifier:bed_files; 77, identifier:bt; 78, identifier:BedTool; 79, call; 80, attribute; 81, argument_list; 82, attribute; 83, argument_list; 84, attribute; 85, argument_list; 86, call; 87, return_statement; 88, attribute; 89, argument_list; 90, identifier:catted; 91, identifier:cat; 92, call; 93, keyword_argument; 94, keyword_argument; 95, identifier:catted; 96, identifier:sort; 97, attribute; 98, identifier:endswith; 99, string:".bed"; 100, attribute; 101, argument_list; 102, identifier:sorted_bed; 103, identifier:bed_files; 104, identifier:pop; 105, attribute; 106, argument_list; 107, identifier:postmerge; 108, False; 109, identifier:force_truncate; 110, False; 111, identifier:sorted_bed; 112, identifier:fn; 113, identifier:sorted_bed; 114, identifier:moveto; 115, binary_operator:sorted_bed.fn + ".bed"; 116, identifier:bed_files; 117, identifier:pop; 118, attribute; 119, string:".bed"; 120, identifier:sorted_bed; 121, identifier:fn | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 8, 15; 9, 16; 9, 17; 10, 18; 10, 19; 10, 20; 11, 21; 15, 22; 15, 23; 16, 24; 16, 25; 17, 26; 18, 27; 19, 28; 19, 29; 20, 30; 21, 31; 21, 32; 23, 33; 23, 34; 23, 35; 24, 36; 24, 37; 26, 38; 26, 39; 26, 40; 26, 41; 28, 42; 29, 43; 30, 44; 32, 45; 32, 46; 34, 47; 34, 48; 35, 49; 37, 50; 40, 51; 40, 52; 41, 53; 42, 54; 42, 55; 43, 56; 43, 57; 44, 58; 51, 59; 52, 60; 52, 61; 52, 62; 53, 63; 55, 64; 55, 65; 57, 66; 57, 67; 58, 68; 58, 69; 59, 70; 59, 71; 60, 72; 61, 73; 62, 74; 63, 75; 65, 76; 66, 77; 66, 78; 67, 79; 69, 80; 69, 81; 71, 82; 71, 83; 72, 84; 72, 85; 73, 86; 74, 87; 79, 88; 79, 89; 80, 90; 80, 91; 81, 92; 81, 93; 81, 94; 82, 95; 82, 96; 84, 97; 84, 98; 85, 99; 86, 100; 86, 101; 87, 102; 88, 103; 88, 104; 92, 105; 92, 106; 93, 107; 93, 108; 94, 109; 94, 110; 97, 111; 97, 112; 100, 113; 100, 114; 101, 115; 105, 116; 105, 117; 115, 118; 115, 119; 118, 120; 118, 121 | def concat(bed_files, catted=None):
"""
recursively concat a set of BED files, returning a
sorted bedtools object of the result
"""
bed_files = [x for x in bed_files if x]
if len(bed_files) == 0:
if catted:
# move to a .bed extension for downstream tools if not already
sorted_bed = catted.sort()
if not sorted_bed.fn.endswith(".bed"):
return sorted_bed.moveto(sorted_bed.fn + ".bed")
else:
return sorted_bed
else:
return catted
if not catted:
bed_files = list(bed_files)
catted = bt.BedTool(bed_files.pop())
else:
catted = catted.cat(bed_files.pop(), postmerge=False,
force_truncate=False)
return concat(bed_files, catted) |
0, module; 1, function_definition; 2, function_name:_get_sv_callers; 3, parameters; 4, block; 5, identifier:items; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""
return a sorted list of all of the structural variant callers run
"""; 11, assignment; 12, identifier:data; 13, identifier:items; 14, block; 15, call; 16, identifier:callers; 17, list; 18, for_statement; 19, attribute; 20, argument_list; 21, identifier:sv; 22, call; 23, block; 24, call; 25, identifier:sort; 26, attribute; 27, argument_list; 28, expression_statement; 29, identifier:list; 30, argument_list; 31, identifier:data; 32, identifier:get; 33, string:"sv"; 34, list; 35, call; 36, call; 37, attribute; 38, argument_list; 39, identifier:set; 40, argument_list; 41, identifier:callers; 42, identifier:append; 43, subscript; 44, list_comprehension; 45, identifier:sv; 46, string:"variantcaller"; 47, identifier:x; 48, for_in_clause; 49, if_clause; 50, identifier:x; 51, identifier:callers; 52, comparison_operator:x != "sv-ensemble"; 53, identifier:x; 54, string:"sv-ensemble" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 9, 15; 11, 16; 11, 17; 14, 18; 15, 19; 15, 20; 18, 21; 18, 22; 18, 23; 19, 24; 19, 25; 22, 26; 22, 27; 23, 28; 24, 29; 24, 30; 26, 31; 26, 32; 27, 33; 27, 34; 28, 35; 30, 36; 35, 37; 35, 38; 36, 39; 36, 40; 37, 41; 37, 42; 38, 43; 40, 44; 43, 45; 43, 46; 44, 47; 44, 48; 44, 49; 48, 50; 48, 51; 49, 52; 52, 53; 52, 54 | def _get_sv_callers(items):
"""
return a sorted list of all of the structural variant callers run
"""
callers = []
for data in items:
for sv in data.get("sv", []):
callers.append(sv["variantcaller"])
return list(set([x for x in callers if x != "sv-ensemble"])).sort() |
0, module; 1, function_definition; 2, function_name:get_sort_cmd; 3, parameters; 4, block; 5, default_parameter; 6, expression_statement; 7, expression_statement; 8, if_statement; 9, if_statement; 10, return_statement; 11, identifier:tmp_dir; 12, None; 13, comment:"""Retrieve GNU coreutils sort command, using version-sort if available.
Recent versions of sort have alpha-numeric sorting, which provides
more natural sorting of chromosomes (chr1, chr2) instead of (chr1, chr10).
This also fixes versions of sort, like 8.22 in CentOS 7.1, that have broken
sorting without version sorting specified.
https://github.com/bcbio/bcbio-nextgen/issues/624
https://github.com/bcbio/bcbio-nextgen/issues/1017
"""; 14, assignment; 15, identifier:has_versionsort; 16, block; 17, else_clause; 18, boolean_operator; 19, block; 20, identifier:cmd; 21, identifier:has_versionsort; 22, call; 23, expression_statement; 24, block; 25, boolean_operator; 26, call; 27, expression_statement; 28, attribute; 29, argument_list; 30, assignment; 31, expression_statement; 32, identifier:tmp_dir; 33, call; 34, attribute; 35, argument_list; 36, augmented_assignment; 37, call; 38, identifier:strip; 39, identifier:cmd; 40, string:"sort -V"; 41, assignment; 42, attribute; 43, argument_list; 44, attribute; 45, identifier:isdir; 46, identifier:tmp_dir; 47, identifier:cmd; 48, binary_operator:" -T %s" % tmp_dir; 49, attribute; 50, argument_list; 51, identifier:cmd; 52, string:"sort"; 53, attribute; 54, identifier:exists; 55, identifier:tmp_dir; 56, identifier:os; 57, identifier:path; 58, string:" -T %s"; 59, identifier:tmp_dir; 60, identifier:subprocess; 61, identifier:check_output; 62, string:"sort --help | grep version-sort; exit 0"; 63, keyword_argument; 64, identifier:os; 65, identifier:path; 66, identifier:shell; 67, True | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 5, 11; 5, 12; 6, 13; 7, 14; 8, 15; 8, 16; 8, 17; 9, 18; 9, 19; 10, 20; 14, 21; 14, 22; 16, 23; 17, 24; 18, 25; 18, 26; 19, 27; 22, 28; 22, 29; 23, 30; 24, 31; 25, 32; 25, 33; 26, 34; 26, 35; 27, 36; 28, 37; 28, 38; 30, 39; 30, 40; 31, 41; 33, 42; 33, 43; 34, 44; 34, 45; 35, 46; 36, 47; 36, 48; 37, 49; 37, 50; 41, 51; 41, 52; 42, 53; 42, 54; 43, 55; 44, 56; 44, 57; 48, 58; 48, 59; 49, 60; 49, 61; 50, 62; 50, 63; 53, 64; 53, 65; 63, 66; 63, 67 | def get_sort_cmd(tmp_dir=None):
"""Retrieve GNU coreutils sort command, using version-sort if available.
Recent versions of sort have alpha-numeric sorting, which provides
more natural sorting of chromosomes (chr1, chr2) instead of (chr1, chr10).
This also fixes versions of sort, like 8.22 in CentOS 7.1, that have broken
sorting without version sorting specified.
https://github.com/bcbio/bcbio-nextgen/issues/624
https://github.com/bcbio/bcbio-nextgen/issues/1017
"""
has_versionsort = subprocess.check_output("sort --help | grep version-sort; exit 0", shell=True).strip()
if has_versionsort:
cmd = "sort -V"
else:
cmd = "sort"
if tmp_dir and os.path.exists(tmp_dir) and os.path.isdir(tmp_dir):
cmd += " -T %s" % tmp_dir
return cmd |
0, module; 1, function_definition; 2, function_name:clean_file; 3, parameters; 4, block; 5, identifier:in_file; 6, identifier:data; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, comment:# Remove non-ascii characters. Used in coverage analysis, to support JSON code in one column; 12, comment:# and be happy with sambamba:; 13, expression_statement; 14, if_statement; 15, identifier:prefix; 16, string:""; 17, identifier:bedprep_dir; 18, None; 19, identifier:simple; 20, None; 21, comment:"""Prepare a clean sorted input BED file without headers
"""; 22, assignment; 23, identifier:in_file; 24, block; 25, identifier:simple; 26, conditional_expression:"iconv -c -f utf-8 -t ascii | sed 's/ //g' |" if simple else ""; 27, if_statement; 28, comment:# Avoid running multiple times with same prefix; 29, if_statement; 30, expression_statement; 31, expression_statement; 32, if_statement; 33, if_statement; 34, expression_statement; 35, return_statement; 36, string:"iconv -c -f utf-8 -t ascii | sed 's/ //g' |"; 37, identifier:simple; 38, string:""; 39, not_operator; 40, block; 41, boolean_operator; 42, block; 43, assignment; 44, assignment; 45, call; 46, block; 47, not_operator; 48, block; 49, call; 50, identifier:out_file; 51, identifier:bedprep_dir; 52, expression_statement; 53, identifier:prefix; 54, call; 55, return_statement; 56, identifier:out_file; 57, call; 58, identifier:out_file; 59, call; 60, attribute; 61, argument_list; 62, expression_statement; 63, call; 64, expression_statement; 65, expression_statement; 66, with_statement; 67, attribute; 68, argument_list; 69, assignment; 70, attribute; 71, argument_list; 72, identifier:in_file; 73, attribute; 74, argument_list; 75, attribute; 76, argument_list; 77, identifier:out_file; 78, identifier:endswith; 79, string:".gz"; 80, assignment; 81, attribute; 82, argument_list; 83, call; 84, call; 85, with_clause; 86, block; 87, identifier:vcfutils; 88, identifier:bgzip_and_index; 89, identifier:out_file; 90, call; 91, keyword_argument; 92, identifier:bedprep_dir; 93, call; 94, call; 95, identifier:startswith; 96, identifier:prefix; 97, attribute; 98, identifier:join; 99, identifier:bedprep_dir; 100, binary_operator:"%s%s" % (prefix, os.path.basename(in_file)); 101, identifier:out_file; 102, identifier:replace; 103, string:".interval_list"; 104, string:".bed"; 105, identifier:out_file; 106, subscript; 107, identifier:utils; 108, identifier:file_uptodate; 109, identifier:out_file; 110, identifier:in_file; 111, identifier:check_bed_contigs; 112, argument_list; 113, identifier:check_bed_coords; 114, argument_list; 115, with_item; 116, expression_statement; 117, expression_statement; 118, expression_statement; 119, expression_statement; 120, expression_statement; 121, attribute; 122, argument_list; 123, identifier:remove_orig; 124, False; 125, attribute; 126, argument_list; 127, attribute; 128, argument_list; 129, identifier:os; 130, identifier:path; 131, string:"%s%s"; 132, tuple; 133, identifier:out_file; 134, slice; 135, identifier:in_file; 136, identifier:data; 137, identifier:in_file; 138, identifier:data; 139, as_pattern; 140, assignment; 141, assignment; 142, assignment; 143, assignment; 144, call; 145, identifier:data; 146, identifier:get; 147, string:"config"; 148, dictionary; 149, identifier:utils; 150, identifier:safe_makedir; 151, call; 152, attribute; 153, identifier:basename; 154, identifier:in_file; 155, identifier:prefix; 156, call; 157, unary_operator; 158, call; 159, as_pattern_target; 160, identifier:bcbio_py; 161, attribute; 162, identifier:cat_cmd; 163, conditional_expression:"zcat" if in_file.endswith(".gz") else "cat"; 164, identifier:sort_cmd; 165, call; 166, identifier:cmd; 167, parenthesized_expression; 168, attribute; 169, argument_list; 170, attribute; 171, argument_list; 172, identifier:os; 173, identifier:path; 174, attribute; 175, argument_list; 176, integer:3; 177, identifier:file_transaction; 178, argument_list; 179, identifier:tx_out_file; 180, identifier:sys; 181, identifier:executable; 182, string:"zcat"; 183, call; 184, string:"cat"; 185, identifier:get_sort_cmd; 186, argument_list; 187, concatenated_string; 188, identifier:do; 189, identifier:run; 190, call; 191, string:"Prepare cleaned BED file"; 192, identifier:data; 193, attribute; 194, identifier:join; 195, subscript; 196, string:"bedprep"; 197, attribute; 198, identifier:basename; 199, identifier:in_file; 200, identifier:data; 201, identifier:out_file; 202, attribute; 203, argument_list; 204, call; 205, string:"{cat_cmd} {in_file} | grep -v ^track | grep -v ^browser | grep -v ^@ | "; 206, string:"grep -v ^# | {simple} "; 207, string:"{bcbio_py} -c 'from bcbio.variation import bedutils; bedutils.remove_bad()' | "; 208, string:"{sort_cmd} -k1,1 -k2,2n > {tx_out_file}"; 209, attribute; 210, argument_list; 211, identifier:os; 212, identifier:path; 213, subscript; 214, string:"work"; 215, identifier:os; 216, identifier:path; 217, identifier:in_file; 218, identifier:endswith; 219, string:".gz"; 220, attribute; 221, argument_list; 222, identifier:cmd; 223, identifier:format; 224, dictionary_splat; 225, identifier:data; 226, string:"dirs"; 227, attribute; 228, identifier:dirname; 229, identifier:tx_out_file; 230, call; 231, identifier:os; 232, identifier:path; 233, identifier:locals; 234, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 7, 15; 7, 16; 8, 17; 8, 18; 9, 19; 9, 20; 10, 21; 13, 22; 14, 23; 14, 24; 22, 25; 22, 26; 24, 27; 24, 28; 24, 29; 24, 30; 24, 31; 24, 32; 24, 33; 24, 34; 24, 35; 26, 36; 26, 37; 26, 38; 27, 39; 27, 40; 29, 41; 29, 42; 30, 43; 31, 44; 32, 45; 32, 46; 33, 47; 33, 48; 34, 49; 35, 50; 39, 51; 40, 52; 41, 53; 41, 54; 42, 55; 43, 56; 43, 57; 44, 58; 44, 59; 45, 60; 45, 61; 46, 62; 47, 63; 48, 64; 48, 65; 48, 66; 49, 67; 49, 68; 52, 69; 54, 70; 54, 71; 55, 72; 57, 73; 57, 74; 59, 75; 59, 76; 60, 77; 60, 78; 61, 79; 62, 80; 63, 81; 63, 82; 64, 83; 65, 84; 66, 85; 66, 86; 67, 87; 67, 88; 68, 89; 68, 90; 68, 91; 69, 92; 69, 93; 70, 94; 70, 95; 71, 96; 73, 97; 73, 98; 74, 99; 74, 100; 75, 101; 75, 102; 76, 103; 76, 104; 80, 105; 80, 106; 81, 107; 81, 108; 82, 109; 82, 110; 83, 111; 83, 112; 84, 113; 84, 114; 85, 115; 86, 116; 86, 117; 86, 118; 86, 119; 86, 120; 90, 121; 90, 122; 91, 123; 91, 124; 93, 125; 93, 126; 94, 127; 94, 128; 97, 129; 97, 130; 100, 131; 100, 132; 106, 133; 106, 134; 112, 135; 112, 136; 114, 137; 114, 138; 115, 139; 116, 140; 117, 141; 118, 142; 119, 143; 120, 144; 121, 145; 121, 146; 122, 147; 122, 148; 125, 149; 125, 150; 126, 151; 127, 152; 127, 153; 128, 154; 132, 155; 132, 156; 134, 157; 139, 158; 139, 159; 140, 160; 140, 161; 141, 162; 141, 163; 142, 164; 142, 165; 143, 166; 143, 167; 144, 168; 144, 169; 151, 170; 151, 171; 152, 172; 152, 173; 156, 174; 156, 175; 157, 176; 158, 177; 158, 178; 159, 179; 161, 180; 161, 181; 163, 182; 163, 183; 163, 184; 165, 185; 165, 186; 167, 187; 168, 188; 168, 189; 169, 190; 169, 191; 169, 192; 170, 193; 170, 194; 171, 195; 171, 196; 174, 197; 174, 198; 175, 199; 178, 200; 178, 201; 183, 202; 183, 203; 186, 204; 187, 205; 187, 206; 187, 207; 187, 208; 190, 209; 190, 210; 193, 211; 193, 212; 195, 213; 195, 214; 197, 215; 197, 216; 202, 217; 202, 218; 203, 219; 204, 220; 204, 221; 209, 222; 209, 223; 210, 224; 213, 225; 213, 226; 220, 227; 220, 228; 221, 229; 224, 230; 227, 231; 227, 232; 230, 233; 230, 234 | def clean_file(in_file, data, prefix="", bedprep_dir=None, simple=None):
"""Prepare a clean sorted input BED file without headers
"""
# Remove non-ascii characters. Used in coverage analysis, to support JSON code in one column
# and be happy with sambamba:
simple = "iconv -c -f utf-8 -t ascii | sed 's/ //g' |" if simple else ""
if in_file:
if not bedprep_dir:
bedprep_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "bedprep"))
# Avoid running multiple times with same prefix
if prefix and os.path.basename(in_file).startswith(prefix):
return in_file
out_file = os.path.join(bedprep_dir, "%s%s" % (prefix, os.path.basename(in_file)))
out_file = out_file.replace(".interval_list", ".bed")
if out_file.endswith(".gz"):
out_file = out_file[:-3]
if not utils.file_uptodate(out_file, in_file):
check_bed_contigs(in_file, data)
check_bed_coords(in_file, data)
with file_transaction(data, out_file) as tx_out_file:
bcbio_py = sys.executable
cat_cmd = "zcat" if in_file.endswith(".gz") else "cat"
sort_cmd = get_sort_cmd(os.path.dirname(tx_out_file))
cmd = ("{cat_cmd} {in_file} | grep -v ^track | grep -v ^browser | grep -v ^@ | "
"grep -v ^# | {simple} "
"{bcbio_py} -c 'from bcbio.variation import bedutils; bedutils.remove_bad()' | "
"{sort_cmd} -k1,1 -k2,2n > {tx_out_file}")
do.run(cmd.format(**locals()), "Prepare cleaned BED file", data)
vcfutils.bgzip_and_index(out_file, data.get("config", {}), remove_orig=False)
return out_file |
0, module; 1, function_definition; 2, function_name:_sort_by_region; 3, parameters; 4, block; 5, identifier:fnames; 6, identifier:regions; 7, identifier:ref_file; 8, identifier:config; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, expression_statement; 13, assert_statement; 14, expression_statement; 15, for_statement; 16, expression_statement; 17, return_statement; 18, comment:"""Sort a set of regionally split files by region for ordered output.
"""; 19, assignment; 20, pattern_list; 21, call; 22, block; 23, assignment; 24, comparison_operator:len(regions) == len(fnames); 25, tuple; 26, assignment; 27, pattern_list; 28, call; 29, block; 30, call; 31, list_comprehension; 32, identifier:contig_order; 33, dictionary; 34, identifier:i; 35, identifier:sq; 36, identifier:enumerate; 37, argument_list; 38, expression_statement; 39, identifier:sitems; 40, list; 41, call; 42, call; 43, identifier:regions; 44, identifier:fnames; 45, identifier:added_fnames; 46, call; 47, identifier:region; 48, identifier:fname; 49, identifier:zip; 50, argument_list; 51, if_statement; 52, attribute; 53, argument_list; 54, tuple; 55, for_in_clause; 56, call; 57, assignment; 58, identifier:len; 59, argument_list; 60, identifier:len; 61, argument_list; 62, identifier:set; 63, argument_list; 64, identifier:regions; 65, identifier:fnames; 66, comparison_operator:fname not in added_fnames; 67, block; 68, identifier:sitems; 69, identifier:sort; 70, subscript; 71, subscript; 72, identifier:x; 73, identifier:sitems; 74, attribute; 75, argument_list; 76, subscript; 77, identifier:i; 78, identifier:regions; 79, identifier:fnames; 80, list; 81, identifier:fname; 82, identifier:added_fnames; 83, if_statement; 84, expression_statement; 85, expression_statement; 86, identifier:x; 87, integer:1; 88, identifier:x; 89, integer:2; 90, identifier:ref; 91, identifier:file_contigs; 92, identifier:ref_file; 93, identifier:config; 94, identifier:contig_order; 95, attribute; 96, call; 97, block; 98, elif_clause; 99, else_clause; 100, call; 101, call; 102, identifier:sq; 103, identifier:name; 104, identifier:isinstance; 105, argument_list; 106, expression_statement; 107, boolean_operator; 108, block; 109, block; 110, attribute; 111, argument_list; 112, attribute; 113, argument_list; 114, identifier:region; 115, tuple; 116, assignment; 117, call; 118, comparison_operator:region.find(":") >= 0; 119, expression_statement; 120, expression_statement; 121, expression_statement; 122, expression_statement; 123, identifier:sitems; 124, identifier:append; 125, tuple; 126, identifier:added_fnames; 127, identifier:add; 128, identifier:fname; 129, identifier:list; 130, identifier:tuple; 131, pattern_list; 132, identifier:region; 133, identifier:isinstance; 134, argument_list; 135, call; 136, integer:0; 137, assignment; 138, assignment; 139, assignment; 140, assignment; 141, tuple; 142, identifier:c; 143, identifier:fname; 144, identifier:c; 145, identifier:s; 146, identifier:e; 147, identifier:region; 148, attribute; 149, attribute; 150, argument_list; 151, pattern_list; 152, call; 153, pattern_list; 154, list_comprehension; 155, identifier:c; 156, identifier:region; 157, pattern_list; 158, expression_list; 159, subscript; 160, identifier:s; 161, identifier:e; 162, identifier:six; 163, identifier:string_types; 164, identifier:region; 165, identifier:find; 166, string:":"; 167, identifier:c; 168, identifier:coords; 169, attribute; 170, argument_list; 171, identifier:s; 172, identifier:e; 173, call; 174, for_in_clause; 175, identifier:s; 176, identifier:e; 177, integer:0; 178, integer:0; 179, identifier:contig_order; 180, identifier:c; 181, identifier:region; 182, identifier:split; 183, string:":"; 184, identifier:int; 185, argument_list; 186, identifier:x; 187, call; 188, identifier:x; 189, attribute; 190, argument_list; 191, identifier:coords; 192, identifier:split; 193, string:"-" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 9, 18; 10, 19; 11, 20; 11, 21; 11, 22; 12, 23; 13, 24; 13, 25; 14, 26; 15, 27; 15, 28; 15, 29; 16, 30; 17, 31; 19, 32; 19, 33; 20, 34; 20, 35; 21, 36; 21, 37; 22, 38; 23, 39; 23, 40; 24, 41; 24, 42; 25, 43; 25, 44; 26, 45; 26, 46; 27, 47; 27, 48; 28, 49; 28, 50; 29, 51; 30, 52; 30, 53; 31, 54; 31, 55; 37, 56; 38, 57; 41, 58; 41, 59; 42, 60; 42, 61; 46, 62; 46, 63; 50, 64; 50, 65; 51, 66; 51, 67; 52, 68; 52, 69; 54, 70; 54, 71; 55, 72; 55, 73; 56, 74; 56, 75; 57, 76; 57, 77; 59, 78; 61, 79; 63, 80; 66, 81; 66, 82; 67, 83; 67, 84; 67, 85; 70, 86; 70, 87; 71, 88; 71, 89; 74, 90; 74, 91; 75, 92; 75, 93; 76, 94; 76, 95; 83, 96; 83, 97; 83, 98; 83, 99; 84, 100; 85, 101; 95, 102; 95, 103; 96, 104; 96, 105; 97, 106; 98, 107; 98, 108; 99, 109; 100, 110; 100, 111; 101, 112; 101, 113; 105, 114; 105, 115; 106, 116; 107, 117; 107, 118; 108, 119; 108, 120; 109, 121; 109, 122; 110, 123; 110, 124; 111, 125; 112, 126; 112, 127; 113, 128; 115, 129; 115, 130; 116, 131; 116, 132; 117, 133; 117, 134; 118, 135; 118, 136; 119, 137; 120, 138; 121, 139; 122, 140; 125, 141; 125, 142; 125, 143; 131, 144; 131, 145; 131, 146; 134, 147; 134, 148; 135, 149; 135, 150; 137, 151; 137, 152; 138, 153; 138, 154; 139, 155; 139, 156; 140, 157; 140, 158; 141, 159; 141, 160; 141, 161; 148, 162; 148, 163; 149, 164; 149, 165; 150, 166; 151, 167; 151, 168; 152, 169; 152, 170; 153, 171; 153, 172; 154, 173; 154, 174; 157, 175; 157, 176; 158, 177; 158, 178; 159, 179; 159, 180; 169, 181; 169, 182; 170, 183; 173, 184; 173, 185; 174, 186; 174, 187; 185, 188; 187, 189; 187, 190; 189, 191; 189, 192; 190, 193 | def _sort_by_region(fnames, regions, ref_file, config):
"""Sort a set of regionally split files by region for ordered output.
"""
contig_order = {}
for i, sq in enumerate(ref.file_contigs(ref_file, config)):
contig_order[sq.name] = i
sitems = []
assert len(regions) == len(fnames), (regions, fnames)
added_fnames = set([])
for region, fname in zip(regions, fnames):
if fname not in added_fnames:
if isinstance(region, (list, tuple)):
c, s, e = region
elif isinstance(region, six.string_types) and region.find(":") >= 0:
c, coords = region.split(":")
s, e = [int(x) for x in coords.split("-")]
else:
c = region
s, e = 0, 0
sitems.append(((contig_order[c], s, e), c, fname))
added_fnames.add(fname)
sitems.sort()
return [(x[1], x[2]) for x in sitems] |
0, module; 1, function_definition; 2, function_name:_get_file_list; 3, parameters; 4, block; 5, identifier:orig_files; 6, identifier:out_file; 7, identifier:regions; 8, identifier:ref_file; 9, identifier:config; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, expression_statement; 15, expression_statement; 16, with_statement; 17, return_statement; 18, comment:"""Create file with region sorted list of non-empty VCFs for concatenating.
"""; 19, assignment; 20, assignment; 21, comparison_operator:len(exist_files) == 0; 22, comment:# no non-empty inputs, merge the empty ones; 23, block; 24, elif_clause; 25, else_clause; 26, assignment; 27, assignment; 28, with_clause; 29, block; 30, identifier:input_file_list; 31, identifier:sorted_files; 32, call; 33, identifier:exist_files; 34, list_comprehension; 35, call; 36, integer:0; 37, expression_statement; 38, comparison_operator:len(exist_files) > 1; 39, block; 40, block; 41, identifier:ready_files; 42, call; 43, identifier:input_file_list; 44, binary_operator:"%s-files.list" % utils.splitext_plus(out_file)[0]; 45, with_item; 46, for_statement; 47, identifier:_sort_by_region; 48, argument_list; 49, tuple; 50, for_in_clause; 51, if_clause; 52, identifier:len; 53, argument_list; 54, assignment; 55, call; 56, integer:1; 57, expression_statement; 58, expression_statement; 59, identifier:run_multicore; 60, argument_list; 61, string:"%s-files.list"; 62, subscript; 63, as_pattern; 64, identifier:fname; 65, identifier:ready_files; 66, block; 67, identifier:orig_files; 68, identifier:regions; 69, identifier:ref_file; 70, identifier:config; 71, identifier:c; 72, identifier:x; 73, pattern_list; 74, identifier:sorted_files; 75, boolean_operator; 76, identifier:exist_files; 77, identifier:exist_files; 78, list_comprehension; 79, identifier:len; 80, argument_list; 81, assignment; 82, assignment; 83, identifier:p_bgzip_and_index; 84, list_comprehension; 85, identifier:config; 86, call; 87, integer:0; 88, call; 89, as_pattern_target; 90, expression_statement; 91, identifier:c; 92, identifier:x; 93, call; 94, call; 95, identifier:x; 96, for_in_clause; 97, if_clause; 98, identifier:exist_files; 99, identifier:exist_files; 100, call; 101, identifier:exist_files; 102, list_comprehension; 103, list; 104, for_in_clause; 105, attribute; 106, argument_list; 107, identifier:open; 108, argument_list; 109, identifier:out_handle; 110, call; 111, attribute; 112, argument_list; 113, identifier:vcf_has_variants; 114, argument_list; 115, pattern_list; 116, identifier:sorted_files; 117, call; 118, identifier:_fix_gatk_header; 119, argument_list; 120, identifier:x; 121, for_in_clause; 122, identifier:x; 123, identifier:config; 124, identifier:x; 125, identifier:exist_files; 126, identifier:utils; 127, identifier:splitext_plus; 128, identifier:out_file; 129, identifier:input_file_list; 130, string:"w"; 131, attribute; 132, argument_list; 133, attribute; 134, identifier:exists; 135, identifier:x; 136, identifier:x; 137, identifier:c; 138, identifier:x; 139, attribute; 140, argument_list; 141, identifier:exist_files; 142, identifier:out_file; 143, identifier:config; 144, pattern_list; 145, identifier:exist_files; 146, identifier:out_handle; 147, identifier:write; 148, binary_operator:fname + "\n"; 149, identifier:os; 150, identifier:path; 151, attribute; 152, identifier:exists; 153, identifier:x; 154, identifier:c; 155, identifier:x; 156, identifier:fname; 157, string:"\n"; 158, identifier:os; 159, identifier:path | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 10, 18; 11, 19; 12, 20; 13, 21; 13, 22; 13, 23; 13, 24; 13, 25; 14, 26; 15, 27; 16, 28; 16, 29; 17, 30; 19, 31; 19, 32; 20, 33; 20, 34; 21, 35; 21, 36; 23, 37; 24, 38; 24, 39; 25, 40; 26, 41; 26, 42; 27, 43; 27, 44; 28, 45; 29, 46; 32, 47; 32, 48; 34, 49; 34, 50; 34, 51; 35, 52; 35, 53; 37, 54; 38, 55; 38, 56; 39, 57; 40, 58; 42, 59; 42, 60; 44, 61; 44, 62; 45, 63; 46, 64; 46, 65; 46, 66; 48, 67; 48, 68; 48, 69; 48, 70; 49, 71; 49, 72; 50, 73; 50, 74; 51, 75; 53, 76; 54, 77; 54, 78; 55, 79; 55, 80; 57, 81; 58, 82; 60, 83; 60, 84; 60, 85; 62, 86; 62, 87; 63, 88; 63, 89; 66, 90; 73, 91; 73, 92; 75, 93; 75, 94; 78, 95; 78, 96; 78, 97; 80, 98; 81, 99; 81, 100; 82, 101; 82, 102; 84, 103; 84, 104; 86, 105; 86, 106; 88, 107; 88, 108; 89, 109; 90, 110; 93, 111; 93, 112; 94, 113; 94, 114; 96, 115; 96, 116; 97, 117; 100, 118; 100, 119; 102, 120; 102, 121; 103, 122; 103, 123; 104, 124; 104, 125; 105, 126; 105, 127; 106, 128; 108, 129; 108, 130; 110, 131; 110, 132; 111, 133; 111, 134; 112, 135; 114, 136; 115, 137; 115, 138; 117, 139; 117, 140; 119, 141; 119, 142; 119, 143; 121, 144; 121, 145; 131, 146; 131, 147; 132, 148; 133, 149; 133, 150; 139, 151; 139, 152; 140, 153; 144, 154; 144, 155; 148, 156; 148, 157; 151, 158; 151, 159 | def _get_file_list(orig_files, out_file, regions, ref_file, config):
"""Create file with region sorted list of non-empty VCFs for concatenating.
"""
sorted_files = _sort_by_region(orig_files, regions, ref_file, config)
exist_files = [(c, x) for c, x in sorted_files if os.path.exists(x) and vcf_has_variants(x)]
if len(exist_files) == 0: # no non-empty inputs, merge the empty ones
exist_files = [x for c, x in sorted_files if os.path.exists(x)]
elif len(exist_files) > 1:
exist_files = _fix_gatk_header(exist_files, out_file, config)
else:
exist_files = [x for c, x in exist_files]
ready_files = run_multicore(p_bgzip_and_index, [[x, config] for x in exist_files], config)
input_file_list = "%s-files.list" % utils.splitext_plus(out_file)[0]
with open(input_file_list, "w") as out_handle:
for fname in ready_files:
out_handle.write(fname + "\n")
return input_file_list |
0, module; 1, function_definition; 2, function_name:sort_by_ref; 3, parameters; 4, block; 5, identifier:vcf_file; 6, identifier:data; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, return_statement; 11, comment:"""Sort a VCF file by genome reference and position, adding contig information.
"""; 12, assignment; 13, not_operator; 14, block; 15, call; 16, identifier:out_file; 17, binary_operator:"%s-prep.vcf.gz" % utils.splitext_plus(vcf_file)[0]; 18, call; 19, with_statement; 20, identifier:bgzip_and_index; 21, argument_list; 22, string:"%s-prep.vcf.gz"; 23, subscript; 24, attribute; 25, argument_list; 26, with_clause; 27, block; 28, identifier:out_file; 29, subscript; 30, call; 31, integer:0; 32, identifier:utils; 33, identifier:file_uptodate; 34, identifier:out_file; 35, identifier:vcf_file; 36, with_item; 37, expression_statement; 38, with_statement; 39, expression_statement; 40, expression_statement; 41, with_statement; 42, identifier:data; 43, string:"config"; 44, attribute; 45, argument_list; 46, as_pattern; 47, assignment; 48, with_clause; 49, block; 50, assignment; 51, assignment; 52, with_clause; 53, block; 54, identifier:utils; 55, identifier:splitext_plus; 56, identifier:vcf_file; 57, call; 58, as_pattern_target; 59, identifier:header_file; 60, binary_operator:"%s-header.txt" % utils.splitext_plus(tx_out_file)[0]; 61, with_item; 62, for_statement; 63, identifier:cat_cmd; 64, conditional_expression:"zcat" if vcf_file.endswith("vcf.gz") else "cat"; 65, identifier:cmd; 66, parenthesized_expression; 67, with_item; 68, expression_statement; 69, identifier:file_transaction; 70, argument_list; 71, identifier:tx_out_file; 72, string:"%s-header.txt"; 73, subscript; 74, as_pattern; 75, identifier:region; 76, call; 77, block; 78, string:"zcat"; 79, call; 80, string:"cat"; 81, concatenated_string; 82, call; 83, call; 84, identifier:data; 85, identifier:out_file; 86, call; 87, integer:0; 88, call; 89, as_pattern_target; 90, attribute; 91, argument_list; 92, expression_statement; 93, attribute; 94, argument_list; 95, string:"{cat_cmd} {vcf_file} | grep -v ^##contig | bcftools annotate -h {header_file} | "; 96, string:"vt sort -m full -o {tx_out_file} -"; 97, attribute; 98, argument_list; 99, attribute; 100, argument_list; 101, attribute; 102, argument_list; 103, identifier:open; 104, argument_list; 105, identifier:out_handle; 106, identifier:ref; 107, identifier:file_contigs; 108, call; 109, subscript; 110, call; 111, identifier:vcf_file; 112, identifier:endswith; 113, string:"vcf.gz"; 114, identifier:utils; 115, identifier:chdir; 116, call; 117, identifier:do; 118, identifier:run; 119, call; 120, string:"Sort VCF by reference"; 121, identifier:utils; 122, identifier:splitext_plus; 123, identifier:tx_out_file; 124, identifier:header_file; 125, string:"w"; 126, attribute; 127, argument_list; 128, identifier:data; 129, string:"config"; 130, attribute; 131, argument_list; 132, attribute; 133, argument_list; 134, attribute; 135, argument_list; 136, identifier:dd; 137, identifier:get_ref_file; 138, identifier:data; 139, identifier:out_handle; 140, identifier:write; 141, binary_operator:"##contig=<ID=%s,length=%s>\n" % (region.name, region.size); 142, attribute; 143, identifier:dirname; 144, identifier:tx_out_file; 145, identifier:cmd; 146, identifier:format; 147, dictionary_splat; 148, string:"##contig=<ID=%s,length=%s>\n"; 149, tuple; 150, identifier:os; 151, identifier:path; 152, call; 153, attribute; 154, attribute; 155, identifier:locals; 156, argument_list; 157, identifier:region; 158, identifier:name; 159, identifier:region; 160, identifier:size | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 9, 14; 10, 15; 12, 16; 12, 17; 13, 18; 14, 19; 15, 20; 15, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 19, 27; 21, 28; 21, 29; 23, 30; 23, 31; 24, 32; 24, 33; 25, 34; 25, 35; 26, 36; 27, 37; 27, 38; 27, 39; 27, 40; 27, 41; 29, 42; 29, 43; 30, 44; 30, 45; 36, 46; 37, 47; 38, 48; 38, 49; 39, 50; 40, 51; 41, 52; 41, 53; 44, 54; 44, 55; 45, 56; 46, 57; 46, 58; 47, 59; 47, 60; 48, 61; 49, 62; 50, 63; 50, 64; 51, 65; 51, 66; 52, 67; 53, 68; 57, 69; 57, 70; 58, 71; 60, 72; 60, 73; 61, 74; 62, 75; 62, 76; 62, 77; 64, 78; 64, 79; 64, 80; 66, 81; 67, 82; 68, 83; 70, 84; 70, 85; 73, 86; 73, 87; 74, 88; 74, 89; 76, 90; 76, 91; 77, 92; 79, 93; 79, 94; 81, 95; 81, 96; 82, 97; 82, 98; 83, 99; 83, 100; 86, 101; 86, 102; 88, 103; 88, 104; 89, 105; 90, 106; 90, 107; 91, 108; 91, 109; 92, 110; 93, 111; 93, 112; 94, 113; 97, 114; 97, 115; 98, 116; 99, 117; 99, 118; 100, 119; 100, 120; 101, 121; 101, 122; 102, 123; 104, 124; 104, 125; 108, 126; 108, 127; 109, 128; 109, 129; 110, 130; 110, 131; 116, 132; 116, 133; 119, 134; 119, 135; 126, 136; 126, 137; 127, 138; 130, 139; 130, 140; 131, 141; 132, 142; 132, 143; 133, 144; 134, 145; 134, 146; 135, 147; 141, 148; 141, 149; 142, 150; 142, 151; 147, 152; 149, 153; 149, 154; 152, 155; 152, 156; 153, 157; 153, 158; 154, 159; 154, 160 | def sort_by_ref(vcf_file, data):
"""Sort a VCF file by genome reference and position, adding contig information.
"""
out_file = "%s-prep.vcf.gz" % utils.splitext_plus(vcf_file)[0]
if not utils.file_uptodate(out_file, vcf_file):
with file_transaction(data, out_file) as tx_out_file:
header_file = "%s-header.txt" % utils.splitext_plus(tx_out_file)[0]
with open(header_file, "w") as out_handle:
for region in ref.file_contigs(dd.get_ref_file(data), data["config"]):
out_handle.write("##contig=<ID=%s,length=%s>\n" % (region.name, region.size))
cat_cmd = "zcat" if vcf_file.endswith("vcf.gz") else "cat"
cmd = ("{cat_cmd} {vcf_file} | grep -v ^##contig | bcftools annotate -h {header_file} | "
"vt sort -m full -o {tx_out_file} -")
with utils.chdir(os.path.dirname(tx_out_file)):
do.run(cmd.format(**locals()), "Sort VCF by reference")
return bgzip_and_index(out_file, data["config"]) |
0, module; 1, function_definition; 2, function_name:align_to_sort_bam; 3, parameters; 4, block; 5, identifier:fastq1; 6, identifier:fastq2; 7, identifier:aligner; 8, identifier:data; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, if_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, if_statement; 17, if_statement; 18, return_statement; 19, comment:"""Align to the named genome build, returning a sorted BAM file.
"""; 20, assignment; 21, assignment; 22, call; 23, block; 24, assignment; 25, assignment; 26, assignment; 27, call; 28, block; 29, else_clause; 30, boolean_operator; 31, block; 32, identifier:data; 33, identifier:names; 34, subscript; 35, identifier:align_dir_parts; 36, list; 37, attribute; 38, argument_list; 39, expression_statement; 40, identifier:aligner_index; 41, call; 42, identifier:align_dir; 43, call; 44, identifier:ref_file; 45, call; 46, attribute; 47, argument_list; 48, expression_statement; 49, block; 50, subscript; 51, call; 52, if_statement; 53, for_statement; 54, identifier:data; 55, string:"rgnames"; 56, subscript; 57, string:"align"; 58, subscript; 59, identifier:data; 60, identifier:get; 61, string:"disambiguate"; 62, call; 63, identifier:_get_aligner_index; 64, argument_list; 65, attribute; 66, argument_list; 67, attribute; 68, argument_list; 69, identifier:fastq1; 70, identifier:endswith; 71, string:".bam"; 72, assignment; 73, expression_statement; 74, identifier:data; 75, string:"work_bam"; 76, attribute; 77, argument_list; 78, boolean_operator; 79, comment:# If merging later with with bamsormadup need query sorted inputs; 80, comment:# but CWL requires a bai file. Create a fake one to make it happy.; 81, block; 82, else_clause; 83, identifier:extra; 84, list; 85, block; 86, subscript; 87, string:"work"; 88, identifier:names; 89, string:"sample"; 90, attribute; 91, argument_list; 92, identifier:aligner; 93, identifier:data; 94, identifier:utils; 95, identifier:safe_makedir; 96, call; 97, identifier:tz; 98, identifier:get_in; 99, tuple; 100, identifier:data; 101, identifier:data; 102, call; 103, assignment; 104, identifier:utils; 105, identifier:file_exists; 106, subscript; 107, call; 108, call; 109, expression_statement; 110, block; 111, string:"-sr"; 112, string:"-disc"; 113, expression_statement; 114, if_statement; 115, identifier:data; 116, string:"dirs"; 117, identifier:align_dir_parts; 118, identifier:append; 119, subscript; 120, attribute; 121, argument_list; 122, string:"reference"; 123, string:"fasta"; 124, string:"base"; 125, identifier:_align_from_bam; 126, argument_list; 127, identifier:data; 128, call; 129, identifier:data; 130, string:"work_bam"; 131, attribute; 132, argument_list; 133, attribute; 134, argument_list; 135, call; 136, expression_statement; 137, assignment; 138, call; 139, block; 140, subscript; 141, string:"genome_build"; 142, attribute; 143, identifier:join; 144, list_splat; 145, identifier:fastq1; 146, identifier:aligner; 147, identifier:aligner_index; 148, identifier:ref_file; 149, identifier:names; 150, identifier:align_dir; 151, identifier:data; 152, identifier:_align_from_fastq; 153, argument_list; 154, identifier:data; 155, identifier:get; 156, string:"align_split"; 157, identifier:dd; 158, identifier:get_mark_duplicates; 159, identifier:data; 160, attribute; 161, argument_list; 162, call; 163, identifier:extra_bam; 164, call; 165, attribute; 166, argument_list; 167, expression_statement; 168, identifier:data; 169, string:"disambiguate"; 170, identifier:os; 171, identifier:path; 172, identifier:align_dir_parts; 173, identifier:fastq1; 174, identifier:fastq2; 175, identifier:aligner; 176, identifier:aligner_index; 177, identifier:ref_file; 178, identifier:names; 179, identifier:align_dir; 180, identifier:data; 181, identifier:bam; 182, identifier:fake_index; 183, subscript; 184, identifier:data; 185, attribute; 186, argument_list; 187, attribute; 188, argument_list; 189, identifier:utils; 190, identifier:file_exists; 191, identifier:extra_bam; 192, call; 193, identifier:data; 194, string:"work_bam"; 195, identifier:bam; 196, identifier:index; 197, subscript; 198, subscript; 199, identifier:utils; 200, identifier:append_stem; 201, subscript; 202, identifier:extra; 203, attribute; 204, argument_list; 205, identifier:data; 206, string:"work_bam"; 207, identifier:data; 208, string:"config"; 209, identifier:data; 210, string; 211, identifier:bam; 212, identifier:index; 213, identifier:extra_bam; 214, subscript; 215, string_content:work_bam; 216, identifier:data; 217, string:"config" | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 9, 19; 10, 20; 11, 21; 12, 22; 12, 23; 13, 24; 14, 25; 15, 26; 16, 27; 16, 28; 16, 29; 17, 30; 17, 31; 18, 32; 20, 33; 20, 34; 21, 35; 21, 36; 22, 37; 22, 38; 23, 39; 24, 40; 24, 41; 25, 42; 25, 43; 26, 44; 26, 45; 27, 46; 27, 47; 28, 48; 29, 49; 30, 50; 30, 51; 31, 52; 31, 53; 34, 54; 34, 55; 36, 56; 36, 57; 36, 58; 37, 59; 37, 60; 38, 61; 39, 62; 41, 63; 41, 64; 43, 65; 43, 66; 45, 67; 45, 68; 46, 69; 46, 70; 47, 71; 48, 72; 49, 73; 50, 74; 50, 75; 51, 76; 51, 77; 52, 78; 52, 79; 52, 80; 52, 81; 52, 82; 53, 83; 53, 84; 53, 85; 56, 86; 56, 87; 58, 88; 58, 89; 62, 90; 62, 91; 64, 92; 64, 93; 65, 94; 65, 95; 66, 96; 67, 97; 67, 98; 68, 99; 68, 100; 72, 101; 72, 102; 73, 103; 76, 104; 76, 105; 77, 106; 78, 107; 78, 108; 81, 109; 82, 110; 84, 111; 84, 112; 85, 113; 85, 114; 86, 115; 86, 116; 90, 117; 90, 118; 91, 119; 96, 120; 96, 121; 99, 122; 99, 123; 99, 124; 102, 125; 102, 126; 103, 127; 103, 128; 106, 129; 106, 130; 107, 131; 107, 132; 108, 133; 108, 134; 109, 135; 110, 136; 113, 137; 114, 138; 114, 139; 119, 140; 119, 141; 120, 142; 120, 143; 121, 144; 126, 145; 126, 146; 126, 147; 126, 148; 126, 149; 126, 150; 126, 151; 128, 152; 128, 153; 131, 154; 131, 155; 132, 156; 133, 157; 133, 158; 134, 159; 135, 160; 135, 161; 136, 162; 137, 163; 137, 164; 138, 165; 138, 166; 139, 167; 140, 168; 140, 169; 142, 170; 142, 171; 144, 172; 153, 173; 153, 174; 153, 175; 153, 176; 153, 177; 153, 178; 153, 179; 153, 180; 160, 181; 160, 182; 161, 183; 161, 184; 162, 185; 162, 186; 164, 187; 164, 188; 165, 189; 165, 190; 166, 191; 167, 192; 183, 193; 183, 194; 185, 195; 185, 196; 186, 197; 186, 198; 187, 199; 187, 200; 188, 201; 188, 202; 192, 203; 192, 204; 197, 205; 197, 206; 198, 207; 198, 208; 201, 209; 201, 210; 203, 211; 203, 212; 204, 213; 204, 214; 210, 215; 214, 216; 214, 217 | def align_to_sort_bam(fastq1, fastq2, aligner, data):
"""Align to the named genome build, returning a sorted BAM file.
"""
names = data["rgnames"]
align_dir_parts = [data["dirs"]["work"], "align", names["sample"]]
if data.get("disambiguate"):
align_dir_parts.append(data["disambiguate"]["genome_build"])
aligner_index = _get_aligner_index(aligner, data)
align_dir = utils.safe_makedir(os.path.join(*align_dir_parts))
ref_file = tz.get_in(("reference", "fasta", "base"), data)
if fastq1.endswith(".bam"):
data = _align_from_bam(fastq1, aligner, aligner_index, ref_file,
names, align_dir, data)
else:
data = _align_from_fastq(fastq1, fastq2, aligner, aligner_index, ref_file,
names, align_dir, data)
if data["work_bam"] and utils.file_exists(data["work_bam"]):
if data.get("align_split") and dd.get_mark_duplicates(data):
# If merging later with with bamsormadup need query sorted inputs
# but CWL requires a bai file. Create a fake one to make it happy.
bam.fake_index(data["work_bam"], data)
else:
bam.index(data["work_bam"], data["config"])
for extra in ["-sr", "-disc"]:
extra_bam = utils.append_stem(data['work_bam'], extra)
if utils.file_exists(extra_bam):
bam.index(extra_bam, data["config"])
return data |
0, module; 1, function_definition; 2, function_name:_align_from_fastq; 3, parameters; 4, block; 5, identifier:fastq1; 6, identifier:fastq2; 7, identifier:aligner; 8, identifier:align_ref; 9, identifier:sam_ref; 10, identifier:names; 11, identifier:align_dir; 12, identifier:data; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, comment:# handle align functions that update the main data dictionary in place; 18, if_statement; 19, comment:"""Align from fastq inputs, producing sorted BAM output.
"""; 20, assignment; 21, assignment; 22, assignment; 23, call; 24, block; 25, comment:# handle output of raw SAM files that need to be converted to BAM; 26, else_clause; 27, identifier:config; 28, subscript; 29, identifier:align_fn; 30, attribute; 31, identifier:out; 32, call; 33, identifier:isinstance; 34, argument_list; 35, assert_statement; 36, return_statement; 37, block; 38, identifier:data; 39, string:"config"; 40, subscript; 41, identifier:align_fn; 42, identifier:align_fn; 43, argument_list; 44, identifier:out; 45, identifier:dict; 46, call; 47, tuple; 48, identifier:out; 49, expression_statement; 50, expression_statement; 51, return_statement; 52, identifier:TOOLS; 53, identifier:aligner; 54, identifier:fastq1; 55, identifier:fastq2; 56, identifier:align_ref; 57, identifier:names; 58, identifier:align_dir; 59, identifier:data; 60, attribute; 61, argument_list; 62, call; 63, call; 64, assignment; 65, assignment; 66, identifier:data; 67, identifier:out; 68, identifier:get; 69, string:"work_bam"; 70, attribute; 71, argument_list; 72, attribute; 73, argument_list; 74, identifier:work_bam; 75, call; 76, subscript; 77, call; 78, identifier:dd; 79, identifier:get_sample_name; 80, identifier:data; 81, identifier:out; 82, identifier:get; 83, string:"work_bam"; 84, attribute; 85, argument_list; 86, identifier:data; 87, string:"work_bam"; 88, attribute; 89, argument_list; 90, identifier:bam; 91, identifier:sam_to_bam; 92, identifier:out; 93, identifier:config; 94, identifier:bam; 95, identifier:sort; 96, identifier:work_bam; 97, identifier:config | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 13, 19; 14, 20; 15, 21; 16, 22; 18, 23; 18, 24; 18, 25; 18, 26; 20, 27; 20, 28; 21, 29; 21, 30; 22, 31; 22, 32; 23, 33; 23, 34; 24, 35; 24, 36; 26, 37; 28, 38; 28, 39; 30, 40; 30, 41; 32, 42; 32, 43; 34, 44; 34, 45; 35, 46; 35, 47; 36, 48; 37, 49; 37, 50; 37, 51; 40, 52; 40, 53; 43, 54; 43, 55; 43, 56; 43, 57; 43, 58; 43, 59; 46, 60; 46, 61; 47, 62; 47, 63; 49, 64; 50, 65; 51, 66; 60, 67; 60, 68; 61, 69; 62, 70; 62, 71; 63, 72; 63, 73; 64, 74; 64, 75; 65, 76; 65, 77; 70, 78; 70, 79; 71, 80; 72, 81; 72, 82; 73, 83; 75, 84; 75, 85; 76, 86; 76, 87; 77, 88; 77, 89; 84, 90; 84, 91; 85, 92; 85, 93; 88, 94; 88, 95; 89, 96; 89, 97 | def _align_from_fastq(fastq1, fastq2, aligner, align_ref, sam_ref, names,
align_dir, data):
"""Align from fastq inputs, producing sorted BAM output.
"""
config = data["config"]
align_fn = TOOLS[aligner].align_fn
out = align_fn(fastq1, fastq2, align_ref, names, align_dir, data)
# handle align functions that update the main data dictionary in place
if isinstance(out, dict):
assert out.get("work_bam"), (dd.get_sample_name(data), out.get("work_bam"))
return out
# handle output of raw SAM files that need to be converted to BAM
else:
work_bam = bam.sam_to_bam(out, config)
data["work_bam"] = bam.sort(work_bam, config)
return data |
0, module; 1, function_definition; 2, function_name:picard_prep; 3, parameters; 4, block; 5, identifier:in_bam; 6, identifier:names; 7, identifier:ref_file; 8, identifier:dirs; 9, identifier:data; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, if_statement; 16, expression_statement; 17, expression_statement; 18, return_statement; 19, comment:"""Prepare input BAM using Picard and GATK cleaning tools.
- ReorderSam to reorder file to reference
- AddOrReplaceReadGroups to add read group information and coordinate sort
- PrintReads to filters to remove problem records:
- filterMBQ to remove reads with mismatching bases and base qualities
"""; 20, assignment; 21, assignment; 22, call; 23, assignment; 24, not_operator; 25, block; 26, assignment; 27, assignment; 28, call; 29, identifier:runner; 30, call; 31, identifier:work_dir; 32, call; 33, attribute; 34, argument_list; 35, identifier:reorder_bam; 36, call; 37, call; 38, expression_statement; 39, identifier:reorder_bam; 40, call; 41, identifier:rg_bam; 42, call; 43, identifier:_filter_bad_reads; 44, argument_list; 45, attribute; 46, argument_list; 47, attribute; 48, argument_list; 49, identifier:runner; 50, identifier:run_fn; 51, string:"picard_index_ref"; 52, identifier:ref_file; 53, attribute; 54, argument_list; 55, attribute; 56, argument_list; 57, assignment; 58, attribute; 59, argument_list; 60, attribute; 61, argument_list; 62, identifier:rg_bam; 63, identifier:ref_file; 64, identifier:data; 65, identifier:broad; 66, identifier:runner_from_path; 67, string:"picard"; 68, subscript; 69, identifier:utils; 70, identifier:safe_makedir; 71, call; 72, attribute; 73, identifier:join; 74, identifier:work_dir; 75, binary_operator:"%s-reorder.bam" %
os.path.splitext(os.path.basename(in_bam))[0]; 76, identifier:utils; 77, identifier:file_exists; 78, identifier:reorder_bam; 79, identifier:reorder_bam; 80, call; 81, identifier:runner; 82, identifier:run_fn; 83, string:"picard_reorder"; 84, identifier:in_bam; 85, identifier:ref_file; 86, identifier:reorder_bam; 87, identifier:runner; 88, identifier:run_fn; 89, string:"picard_fix_rgs"; 90, identifier:reorder_bam; 91, identifier:names; 92, identifier:data; 93, string:"config"; 94, attribute; 95, argument_list; 96, identifier:os; 97, identifier:path; 98, string:"%s-reorder.bam"; 99, subscript; 100, attribute; 101, argument_list; 102, attribute; 103, identifier:join; 104, subscript; 105, string:"bamclean"; 106, subscript; 107, call; 108, integer:0; 109, attribute; 110, identifier:join; 111, identifier:work_dir; 112, binary_operator:"%s-reorder.bam" % dd.get_sample_name(data); 113, identifier:os; 114, identifier:path; 115, identifier:dirs; 116, string:"work"; 117, identifier:names; 118, string:"sample"; 119, attribute; 120, argument_list; 121, identifier:os; 122, identifier:path; 123, string:"%s-reorder.bam"; 124, call; 125, attribute; 126, identifier:splitext; 127, call; 128, attribute; 129, argument_list; 130, identifier:os; 131, identifier:path; 132, attribute; 133, argument_list; 134, identifier:dd; 135, identifier:get_sample_name; 136, identifier:data; 137, attribute; 138, identifier:basename; 139, identifier:in_bam; 140, identifier:os; 141, identifier:path | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 10, 19; 11, 20; 12, 21; 13, 22; 14, 23; 15, 24; 15, 25; 16, 26; 17, 27; 18, 28; 20, 29; 20, 30; 21, 31; 21, 32; 22, 33; 22, 34; 23, 35; 23, 36; 24, 37; 25, 38; 26, 39; 26, 40; 27, 41; 27, 42; 28, 43; 28, 44; 30, 45; 30, 46; 32, 47; 32, 48; 33, 49; 33, 50; 34, 51; 34, 52; 36, 53; 36, 54; 37, 55; 37, 56; 38, 57; 40, 58; 40, 59; 42, 60; 42, 61; 44, 62; 44, 63; 44, 64; 45, 65; 45, 66; 46, 67; 46, 68; 47, 69; 47, 70; 48, 71; 53, 72; 53, 73; 54, 74; 54, 75; 55, 76; 55, 77; 56, 78; 57, 79; 57, 80; 58, 81; 58, 82; 59, 83; 59, 84; 59, 85; 59, 86; 60, 87; 60, 88; 61, 89; 61, 90; 61, 91; 68, 92; 68, 93; 71, 94; 71, 95; 72, 96; 72, 97; 75, 98; 75, 99; 80, 100; 80, 101; 94, 102; 94, 103; 95, 104; 95, 105; 95, 106; 99, 107; 99, 108; 100, 109; 100, 110; 101, 111; 101, 112; 102, 113; 102, 114; 104, 115; 104, 116; 106, 117; 106, 118; 107, 119; 107, 120; 109, 121; 109, 122; 112, 123; 112, 124; 119, 125; 119, 126; 120, 127; 124, 128; 124, 129; 125, 130; 125, 131; 127, 132; 127, 133; 128, 134; 128, 135; 129, 136; 132, 137; 132, 138; 133, 139; 137, 140; 137, 141 | def picard_prep(in_bam, names, ref_file, dirs, data):
"""Prepare input BAM using Picard and GATK cleaning tools.
- ReorderSam to reorder file to reference
- AddOrReplaceReadGroups to add read group information and coordinate sort
- PrintReads to filters to remove problem records:
- filterMBQ to remove reads with mismatching bases and base qualities
"""
runner = broad.runner_from_path("picard", data["config"])
work_dir = utils.safe_makedir(os.path.join(dirs["work"], "bamclean", names["sample"]))
runner.run_fn("picard_index_ref", ref_file)
reorder_bam = os.path.join(work_dir, "%s-reorder.bam" %
os.path.splitext(os.path.basename(in_bam))[0])
if not utils.file_exists(reorder_bam):
reorder_bam = os.path.join(work_dir, "%s-reorder.bam" % dd.get_sample_name(data))
reorder_bam = runner.run_fn("picard_reorder", in_bam, ref_file, reorder_bam)
rg_bam = runner.run_fn("picard_fix_rgs", reorder_bam, names)
return _filter_bad_reads(rg_bam, ref_file, data) |
0, module; 1, function_definition; 2, function_name:iterate_flattened_separately; 3, parameters; 4, block; 5, identifier:dictionary; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, for_statement; 10, expression_statement; 11, for_statement; 12, expression_statement; 13, for_statement; 14, identifier:manually_sorted_keys; 15, None; 16, comment:"""
Recursively iterate over the items of a dictionary in a special order.
First iterate over manually sorted keys and then over all items that are
non-dictionary values (sorted by keys), then over the rest
(sorted by keys), providing full dotted paths for every leaf.
"""; 17, comparison_operator:manually_sorted_keys is None; 18, block; 19, identifier:key; 20, identifier:manually_sorted_keys; 21, block; 22, assignment; 23, identifier:key; 24, call; 25, block; 26, assignment; 27, identifier:key; 28, call; 29, block; 30, identifier:manually_sorted_keys; 31, None; 32, expression_statement; 33, if_statement; 34, identifier:single_line_keys; 35, list_comprehension; 36, identifier:sorted; 37, argument_list; 38, expression_statement; 39, identifier:multi_line_keys; 40, list_comprehension; 41, identifier:sorted; 42, argument_list; 43, expression_statement; 44, for_statement; 45, assignment; 46, comparison_operator:key in dictionary; 47, block; 48, identifier:key; 49, for_in_clause; 50, if_clause; 51, identifier:single_line_keys; 52, yield; 53, identifier:key; 54, for_in_clause; 55, if_clause; 56, identifier:multi_line_keys; 57, yield; 58, pattern_list; 59, call; 60, block; 61, identifier:manually_sorted_keys; 62, list; 63, identifier:key; 64, identifier:dictionary; 65, expression_statement; 66, identifier:key; 67, call; 68, boolean_operator; 69, expression_list; 70, identifier:key; 71, call; 72, boolean_operator; 73, expression_list; 74, identifier:k; 75, identifier:val; 76, identifier:iterate_flattened_separately; 77, argument_list; 78, expression_statement; 79, yield; 80, attribute; 81, argument_list; 82, comparison_operator:key not in manually_sorted_keys; 83, parenthesized_expression; 84, identifier:key; 85, subscript; 86, attribute; 87, argument_list; 88, comparison_operator:key not in manually_sorted_keys; 89, parenthesized_expression; 90, identifier:key; 91, identifier:PATHCHANGE; 92, subscript; 93, identifier:manually_sorted_keys; 94, yield; 95, expression_list; 96, identifier:dictionary; 97, identifier:keys; 98, identifier:key; 99, identifier:manually_sorted_keys; 100, boolean_operator; 101, identifier:dictionary; 102, identifier:key; 103, identifier:dictionary; 104, identifier:keys; 105, identifier:key; 106, identifier:manually_sorted_keys; 107, boolean_operator; 108, identifier:dictionary; 109, identifier:key; 110, expression_list; 111, identifier:key; 112, subscript; 113, not_operator; 114, not_operator; 115, subscript; 116, call; 117, call; 118, identifier:val; 119, identifier:dictionary; 120, identifier:key; 121, subscript; 122, call; 123, identifier:dictionary; 124, identifier:key; 125, identifier:isinstance; 126, argument_list; 127, identifier:join_paths; 128, argument_list; 129, identifier:dictionary; 130, identifier:key; 131, identifier:isinstance; 132, argument_list; 133, subscript; 134, identifier:dict; 135, identifier:key; 136, identifier:k; 137, subscript; 138, identifier:dict; 139, identifier:dictionary; 140, identifier:key; 141, identifier:dictionary; 142, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 6, 15; 7, 16; 8, 17; 8, 18; 9, 19; 9, 20; 9, 21; 10, 22; 11, 23; 11, 24; 11, 25; 12, 26; 13, 27; 13, 28; 13, 29; 17, 30; 17, 31; 18, 32; 21, 33; 22, 34; 22, 35; 24, 36; 24, 37; 25, 38; 26, 39; 26, 40; 28, 41; 28, 42; 29, 43; 29, 44; 32, 45; 33, 46; 33, 47; 35, 48; 35, 49; 35, 50; 37, 51; 38, 52; 40, 53; 40, 54; 40, 55; 42, 56; 43, 57; 44, 58; 44, 59; 44, 60; 45, 61; 45, 62; 46, 63; 46, 64; 47, 65; 49, 66; 49, 67; 50, 68; 52, 69; 54, 70; 54, 71; 55, 72; 57, 73; 58, 74; 58, 75; 59, 76; 59, 77; 60, 78; 65, 79; 67, 80; 67, 81; 68, 82; 68, 83; 69, 84; 69, 85; 71, 86; 71, 87; 72, 88; 72, 89; 73, 90; 73, 91; 77, 92; 77, 93; 78, 94; 79, 95; 80, 96; 80, 97; 82, 98; 82, 99; 83, 100; 85, 101; 85, 102; 86, 103; 86, 104; 88, 105; 88, 106; 89, 107; 92, 108; 92, 109; 94, 110; 95, 111; 95, 112; 100, 113; 100, 114; 107, 115; 107, 116; 110, 117; 110, 118; 112, 119; 112, 120; 113, 121; 114, 122; 115, 123; 115, 124; 116, 125; 116, 126; 117, 127; 117, 128; 121, 129; 121, 130; 122, 131; 122, 132; 126, 133; 126, 134; 128, 135; 128, 136; 132, 137; 132, 138; 133, 139; 133, 140; 137, 141; 137, 142 | def iterate_flattened_separately(dictionary, manually_sorted_keys=None):
"""
Recursively iterate over the items of a dictionary in a special order.
First iterate over manually sorted keys and then over all items that are
non-dictionary values (sorted by keys), then over the rest
(sorted by keys), providing full dotted paths for every leaf.
"""
if manually_sorted_keys is None:
manually_sorted_keys = []
for key in manually_sorted_keys:
if key in dictionary:
yield key, dictionary[key]
single_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(not dictionary[key] or
not isinstance(dictionary[key], dict))]
for key in sorted(single_line_keys):
yield key, dictionary[key]
multi_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(dictionary[key] and
isinstance(dictionary[key], dict))]
for key in sorted(multi_line_keys):
yield key, PATHCHANGE
for k, val in iterate_flattened_separately(dictionary[key],
manually_sorted_keys):
yield join_paths(key, k), val |
0, module; 1, function_definition; 2, function_name:gather_command_line_options; 3, parameters; 4, block; 5, default_parameter; 6, expression_statement; 7, if_statement; 8, expression_statement; 9, return_statement; 10, identifier:filter_disabled; 11, None; 12, comment:"""Get a sorted list of all CommandLineOption subclasses."""; 13, comparison_operator:filter_disabled is None; 14, block; 15, assignment; 16, call; 17, identifier:filter_disabled; 18, None; 19, expression_statement; 20, identifier:options; 21, list_comprehension; 22, identifier:sorted; 23, argument_list; 24, assignment; 25, identifier:opt; 26, for_in_clause; 27, if_clause; 28, identifier:options; 29, keyword_argument; 30, identifier:filter_disabled; 31, not_operator; 32, identifier:opt; 33, call; 34, boolean_operator; 35, identifier:key; 36, lambda; 37, attribute; 38, identifier:get_inheritors; 39, argument_list; 40, not_operator; 41, attribute; 42, lambda_parameters; 43, attribute; 44, attribute; 45, identifier:SHOW_DISABLED_OPTIONS; 46, identifier:CommandLineOption; 47, identifier:filter_disabled; 48, identifier:opt; 49, identifier:_enabled; 50, identifier:opt; 51, identifier:opt; 52, identifier:__name__; 53, identifier:SETTINGS; 54, identifier:COMMAND_LINE | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 5, 10; 5, 11; 6, 12; 7, 13; 7, 14; 8, 15; 9, 16; 13, 17; 13, 18; 14, 19; 15, 20; 15, 21; 16, 22; 16, 23; 19, 24; 21, 25; 21, 26; 21, 27; 23, 28; 23, 29; 24, 30; 24, 31; 26, 32; 26, 33; 27, 34; 29, 35; 29, 36; 31, 37; 33, 38; 33, 39; 34, 40; 34, 41; 36, 42; 36, 43; 37, 44; 37, 45; 39, 46; 40, 47; 41, 48; 41, 49; 42, 50; 43, 51; 43, 52; 44, 53; 44, 54 | def gather_command_line_options(filter_disabled=None):
"""Get a sorted list of all CommandLineOption subclasses."""
if filter_disabled is None:
filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS
options = [opt for opt in get_inheritors(CommandLineOption)
if not filter_disabled or opt._enabled]
return sorted(options, key=lambda opt: opt.__name__) |
0, module; 1, function_definition; 2, function_name:bar; 3, parameters; 4, block; 5, identifier:df; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, default_parameter; 14, default_parameter; 15, default_parameter; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, comment:# Start appending elements, starting with a modified bottom x axis.; 25, if_statement; 26, comment:# Create the third axis, which displays columnar totals above the rest of the plot.; 27, expression_statement; 28, expression_statement; 29, expression_statement; 30, expression_statement; 31, expression_statement; 32, expression_statement; 33, for_statement; 34, if_statement; 35, identifier:figsize; 36, tuple; 37, identifier:fontsize; 38, integer:16; 39, identifier:labels; 40, None; 41, identifier:log; 42, False; 43, identifier:color; 44, string; 45, identifier:inline; 46, False; 47, identifier:filter; 48, None; 49, identifier:n; 50, integer:0; 51, identifier:p; 52, integer:0; 53, identifier:sort; 54, None; 55, comment:"""
A bar chart visualization of the nullity of the given DataFrame.
:param df: The input DataFrame.
:param log: Whether or not to display a logorithmic plot. Defaults to False (linear).
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default).
:param figsize: The size of the figure to display.
:param fontsize: The figure's font size. This default to 16.
:param labels: Whether or not to display the column names. Would need to be turned off on particularly large
displays. Defaults to True.
:param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""; 56, assignment; 57, assignment; 58, assignment; 59, call; 60, call; 61, assignment; 62, assignment; 63, boolean_operator; 64, block; 65, else_clause; 66, assignment; 67, call; 68, call; 69, call; 70, call; 71, call; 72, identifier:ax; 73, identifier:axes; 74, block; 75, identifier:inline; 76, block; 77, else_clause; 78, integer:24; 79, integer:10; 80, string_content:dimgray; 81, identifier:nullity_counts; 82, binary_operator:len(df) - df.isnull().sum(); 83, identifier:df; 84, call; 85, identifier:df; 86, call; 87, attribute; 88, argument_list; 89, attribute; 90, argument_list; 91, identifier:ax1; 92, call; 93, identifier:axes; 94, list; 95, identifier:labels; 96, parenthesized_expression; 97, expression_statement; 98, comment:# Create the numerical ticks.; 99, expression_statement; 100, expression_statement; 101, if_statement; 102, block; 103, identifier:ax3; 104, call; 105, attribute; 106, argument_list; 107, attribute; 108, argument_list; 109, attribute; 110, argument_list; 111, attribute; 112, argument_list; 113, attribute; 114, argument_list; 115, expression_statement; 116, expression_statement; 117, expression_statement; 118, expression_statement; 119, expression_statement; 120, expression_statement; 121, expression_statement; 122, block; 123, call; 124, call; 125, identifier:nullity_filter; 126, argument_list; 127, identifier:nullity_sort; 128, argument_list; 129, identifier:plt; 130, identifier:figure; 131, keyword_argument; 132, parenthesized_expression; 133, identifier:plot; 134, keyword_argument; 135, keyword_argument; 136, keyword_argument; 137, keyword_argument; 138, keyword_argument; 139, attribute; 140, argument_list; 141, identifier:ax1; 142, boolean_operator; 143, call; 144, assignment; 145, call; 146, not_operator; 147, block; 148, else_clause; 149, expression_statement; 150, attribute; 151, argument_list; 152, identifier:axes; 153, identifier:append; 154, identifier:ax3; 155, identifier:ax3; 156, identifier:set_xticks; 157, call; 158, identifier:ax3; 159, identifier:set_xlim; 160, call; 161, identifier:ax3; 162, identifier:set_xticklabels; 163, attribute; 164, keyword_argument; 165, keyword_argument; 166, keyword_argument; 167, identifier:ax3; 168, identifier:grid; 169, False; 170, call; 171, call; 172, call; 173, call; 174, call; 175, call; 176, call; 177, return_statement; 178, identifier:len; 179, argument_list; 180, attribute; 181, argument_list; 182, identifier:df; 183, keyword_argument; 184, keyword_argument; 185, keyword_argument; 186, identifier:df; 187, keyword_argument; 188, identifier:figsize; 189, identifier:figsize; 190, binary_operator:nullity_counts / len(df); 191, identifier:kind; 192, string; 193, identifier:figsize; 194, identifier:figsize; 195, identifier:fontsize; 196, identifier:fontsize; 197, identifier:log; 198, identifier:log; 199, identifier:color; 200, identifier:color; 201, identifier:plt; 202, identifier:gca; 203, comparison_operator:labels is None; 204, comparison_operator:len(df.columns) <= 50; 205, attribute; 206, argument_list; 207, identifier:ax2; 208, call; 209, attribute; 210, argument_list; 211, identifier:log; 212, expression_statement; 213, expression_statement; 214, expression_statement; 215, comment:# For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually; 216, comment:# appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale; 217, comment:# is used, we have to make it match the `ax1` layout ourselves.; 218, block; 219, call; 220, identifier:ax1; 221, identifier:twiny; 222, attribute; 223, argument_list; 224, attribute; 225, argument_list; 226, identifier:nullity_counts; 227, identifier:values; 228, identifier:fontsize; 229, identifier:fontsize; 230, identifier:rotation; 231, integer:45; 232, identifier:ha; 233, string; 234, attribute; 235, argument_list; 236, attribute; 237, argument_list; 238, attribute; 239, argument_list; 240, attribute; 241, argument_list; 242, attribute; 243, argument_list; 244, attribute; 245, argument_list; 246, attribute; 247, argument_list; 248, identifier:ax1; 249, identifier:df; 250, call; 251, identifier:sum; 252, identifier:filter; 253, identifier:filter; 254, identifier:n; 255, identifier:n; 256, identifier:p; 257, identifier:p; 258, identifier:sort; 259, identifier:sort; 260, identifier:nullity_counts; 261, call; 262, string_content:bar; 263, identifier:labels; 264, None; 265, call; 266, integer:50; 267, identifier:ax1; 268, identifier:set_xticklabels; 269, call; 270, keyword_argument; 271, keyword_argument; 272, keyword_argument; 273, attribute; 274, argument_list; 275, identifier:axes; 276, identifier:append; 277, identifier:ax2; 278, call; 279, call; 280, call; 281, expression_statement; 282, expression_statement; 283, expression_statement; 284, attribute; 285, argument_list; 286, identifier:ax1; 287, identifier:get_xticks; 288, identifier:ax1; 289, identifier:get_xlim; 290, string_content:left; 291, subscript; 292, identifier:set_visible; 293, False; 294, subscript; 295, identifier:set_visible; 296, False; 297, subscript; 298, identifier:set_visible; 299, False; 300, subscript; 301, identifier:set_visible; 302, False; 303, attribute; 304, identifier:set_ticks_position; 305, string; 306, attribute; 307, identifier:set_ticks_position; 308, string; 309, identifier:plt; 310, identifier:show; 311, attribute; 312, argument_list; 313, identifier:len; 314, argument_list; 315, identifier:len; 316, argument_list; 317, attribute; 318, argument_list; 319, identifier:rotation; 320, integer:45; 321, identifier:ha; 322, string; 323, identifier:fontsize; 324, identifier:fontsize; 325, identifier:ax1; 326, identifier:twinx; 327, attribute; 328, argument_list; 329, attribute; 330, argument_list; 331, attribute; 332, argument_list; 333, call; 334, call; 335, call; 336, identifier:ax1; 337, identifier:set_xticks; 338, list; 339, attribute; 340, string; 341, attribute; 342, string; 343, attribute; 344, string; 345, attribute; 346, string; 347, identifier:ax; 348, identifier:xaxis; 349, string_content:none; 350, identifier:ax; 351, identifier:yaxis; 352, string_content:none; 353, identifier:df; 354, identifier:isnull; 355, identifier:df; 356, attribute; 357, identifier:ax1; 358, identifier:get_xticklabels; 359, string_content:right; 360, identifier:ax1; 361, identifier:set_ylim; 362, list; 363, identifier:ax2; 364, identifier:set_yticks; 365, call; 366, identifier:ax2; 367, identifier:set_yticklabels; 368, list_comprehension; 369, keyword_argument; 370, attribute; 371, argument_list; 372, attribute; 373, argument_list; 374, attribute; 375, argument_list; 376, identifier:ax; 377, identifier:spines; 378, string_content:top; 379, identifier:ax; 380, identifier:spines; 381, string_content:right; 382, identifier:ax; 383, identifier:spines; 384, string_content:bottom; 385, identifier:ax; 386, identifier:spines; 387, string_content:left; 388, identifier:df; 389, identifier:columns; 390, integer:0; 391, integer:1; 392, attribute; 393, argument_list; 394, call; 395, for_in_clause; 396, identifier:fontsize; 397, identifier:fontsize; 398, identifier:ax2; 399, identifier:set_yscale; 400, string; 401, identifier:ax2; 402, identifier:set_ylim; 403, call; 404, identifier:ax2; 405, identifier:set_yticklabels; 406, list_comprehension; 407, keyword_argument; 408, identifier:ax1; 409, identifier:get_yticks; 410, identifier:int; 411, argument_list; 412, identifier:n; 413, call; 414, string_content:log; 415, attribute; 416, argument_list; 417, call; 418, for_in_clause; 419, identifier:fontsize; 420, identifier:fontsize; 421, binary_operator:n*len(df); 422, attribute; 423, argument_list; 424, identifier:ax1; 425, identifier:get_ylim; 426, identifier:int; 427, argument_list; 428, identifier:n; 429, call; 430, identifier:n; 431, call; 432, identifier:ax1; 433, identifier:get_yticks; 434, binary_operator:n*len(df); 435, attribute; 436, argument_list; 437, identifier:len; 438, argument_list; 439, identifier:n; 440, call; 441, identifier:ax1; 442, identifier:get_yticks; 443, identifier:df; 444, identifier:len; 445, argument_list; 446, identifier:df | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 3, 14; 3, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 4, 30; 4, 31; 4, 32; 4, 33; 4, 34; 6, 35; 6, 36; 7, 37; 7, 38; 8, 39; 8, 40; 9, 41; 9, 42; 10, 43; 10, 44; 11, 45; 11, 46; 12, 47; 12, 48; 13, 49; 13, 50; 14, 51; 14, 52; 15, 53; 15, 54; 16, 55; 17, 56; 18, 57; 19, 58; 20, 59; 21, 60; 22, 61; 23, 62; 25, 63; 25, 64; 25, 65; 27, 66; 28, 67; 29, 68; 30, 69; 31, 70; 32, 71; 33, 72; 33, 73; 33, 74; 34, 75; 34, 76; 34, 77; 36, 78; 36, 79; 44, 80; 56, 81; 56, 82; 57, 83; 57, 84; 58, 85; 58, 86; 59, 87; 59, 88; 60, 89; 60, 90; 61, 91; 61, 92; 62, 93; 62, 94; 63, 95; 63, 96; 64, 97; 64, 98; 64, 99; 64, 100; 64, 101; 65, 102; 66, 103; 66, 104; 67, 105; 67, 106; 68, 107; 68, 108; 69, 109; 69, 110; 70, 111; 70, 112; 71, 113; 71, 114; 74, 115; 74, 116; 74, 117; 74, 118; 74, 119; 74, 120; 76, 121; 77, 122; 82, 123; 82, 124; 84, 125; 84, 126; 86, 127; 86, 128; 87, 129; 87, 130; 88, 131; 89, 132; 89, 133; 90, 134; 90, 135; 90, 136; 90, 137; 90, 138; 92, 139; 92, 140; 94, 141; 96, 142; 97, 143; 99, 144; 100, 145; 101, 146; 101, 147; 101, 148; 102, 149; 104, 150; 104, 151; 105, 152; 105, 153; 106, 154; 107, 155; 107, 156; 108, 157; 109, 158; 109, 159; 110, 160; 111, 161; 111, 162; 112, 163; 112, 164; 112, 165; 112, 166; 113, 167; 113, 168; 114, 169; 115, 170; 116, 171; 117, 172; 118, 173; 119, 174; 120, 175; 121, 176; 122, 177; 123, 178; 123, 179; 124, 180; 124, 181; 126, 182; 126, 183; 126, 184; 126, 185; 128, 186; 128, 187; 131, 188; 131, 189; 132, 190; 134, 191; 134, 192; 135, 193; 135, 194; 136, 195; 136, 196; 137, 197; 137, 198; 138, 199; 138, 200; 139, 201; 139, 202; 142, 203; 142, 204; 143, 205; 143, 206; 144, 207; 144, 208; 145, 209; 145, 210; 146, 211; 147, 212; 147, 213; 147, 214; 148, 215; 148, 216; 148, 217; 148, 218; 149, 219; 150, 220; 150, 221; 157, 222; 157, 223; 160, 224; 160, 225; 163, 226; 163, 227; 164, 228; 164, 229; 165, 230; 165, 231; 166, 232; 166, 233; 170, 234; 170, 235; 171, 236; 171, 237; 172, 238; 172, 239; 173, 240; 173, 241; 174, 242; 174, 243; 175, 244; 175, 245; 176, 246; 176, 247; 177, 248; 179, 249; 180, 250; 180, 251; 183, 252; 183, 253; 184, 254; 184, 255; 185, 256; 185, 257; 187, 258; 187, 259; 190, 260; 190, 261; 192, 262; 203, 263; 203, 264; 204, 265; 204, 266; 205, 267; 205, 268; 206, 269; 206, 270; 206, 271; 206, 272; 208, 273; 208, 274; 209, 275; 209, 276; 210, 277; 212, 278; 213, 279; 214, 280; 218, 281; 218, 282; 218, 283; 219, 284; 219, 285; 222, 286; 222, 287; 224, 288; 224, 289; 233, 290; 234, 291; 234, 292; 235, 293; 236, 294; 236, 295; 237, 296; 238, 297; 238, 298; 239, 299; 240, 300; 240, 301; 241, 302; 242, 303; 242, 304; 243, 305; 244, 306; 244, 307; 245, 308; 246, 309; 246, 310; 250, 311; 250, 312; 261, 313; 261, 314; 265, 315; 265, 316; 269, 317; 269, 318; 270, 319; 270, 320; 271, 321; 271, 322; 272, 323; 272, 324; 273, 325; 273, 326; 278, 327; 278, 328; 279, 329; 279, 330; 280, 331; 280, 332; 281, 333; 282, 334; 283, 335; 284, 336; 284, 337; 285, 338; 291, 339; 291, 340; 294, 341; 294, 342; 297, 343; 297, 344; 300, 345; 300, 346; 303, 347; 303, 348; 305, 349; 306, 350; 306, 351; 308, 352; 311, 353; 311, 354; 314, 355; 316, 356; 317, 357; 317, 358; 322, 359; 327, 360; 327, 361; 328, 362; 329, 363; 329, 364; 330, 365; 331, 366; 331, 367; 332, 368; 332, 369; 333, 370; 333, 371; 334, 372; 334, 373; 335, 374; 335, 375; 339, 376; 339, 377; 340, 378; 341, 379; 341, 380; 342, 381; 343, 382; 343, 383; 344, 384; 345, 385; 345, 386; 346, 387; 356, 388; 356, 389; 362, 390; 362, 391; 365, 392; 365, 393; 368, 394; 368, 395; 369, 396; 369, 397; 370, 398; 370, 399; 371, 400; 372, 401; 372, 402; 373, 403; 374, 404; 374, 405; 375, 406; 375, 407; 392, 408; 392, 409; 394, 410; 394, 411; 395, 412; 395, 413; 400, 414; 403, 415; 403, 416; 406, 417; 406, 418; 407, 419; 407, 420; 411, 421; 413, 422; 413, 423; 415, 424; 415, 425; 417, 426; 417, 427; 418, 428; 418, 429; 421, 430; 421, 431; 422, 432; 422, 433; 427, 434; 429, 435; 429, 436; 431, 437; 431, 438; 434, 439; 434, 440; 435, 441; 435, 442; 438, 443; 440, 444; 440, 445; 445, 446 | def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False,
filter=None, n=0, p=0, sort=None):
"""
A bar chart visualization of the nullity of the given DataFrame.
:param df: The input DataFrame.
:param log: Whether or not to display a logorithmic plot. Defaults to False (linear).
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default).
:param figsize: The size of the figure to display.
:param fontsize: The figure's font size. This default to 16.
:param labels: Whether or not to display the column names. Would need to be turned off on particularly large
displays. Defaults to True.
:param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
nullity_counts = len(df) - df.isnull().sum()
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
plt.figure(figsize=figsize)
(nullity_counts / len(df)).plot(kind='bar', figsize=figsize, fontsize=fontsize, log=log, color=color)
ax1 = plt.gca()
axes = [ax1]
# Start appending elements, starting with a modified bottom x axis.
if labels or (labels is None and len(df.columns) <= 50):
ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='right', fontsize=fontsize)
# Create the numerical ticks.
ax2 = ax1.twinx()
axes.append(ax2)
if not log:
ax1.set_ylim([0, 1])
ax2.set_yticks(ax1.get_yticks())
ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize)
else:
# For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually
# appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale
# is used, we have to make it match the `ax1` layout ourselves.
ax2.set_yscale('log')
ax2.set_ylim(ax1.get_ylim())
ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize)
else:
ax1.set_xticks([])
# Create the third axis, which displays columnar totals above the rest of the plot.
ax3 = ax1.twiny()
axes.append(ax3)
ax3.set_xticks(ax1.get_xticks())
ax3.set_xlim(ax1.get_xlim())
ax3.set_xticklabels(nullity_counts.values, fontsize=fontsize, rotation=45, ha='left')
ax3.grid(False)
for ax in axes:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
if inline:
plt.show()
else:
return ax1 |
0, module; 1, function_definition; 2, function_name:heatmap; 3, parameters; 4, block; 5, identifier:df; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, default_parameter; 14, default_parameter; 15, default_parameter; 16, default_parameter; 17, default_parameter; 18, expression_statement; 19, comment:# Apply filters and sorts, set up the figure.; 20, expression_statement; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, expression_statement; 25, comment:# Remove completely filled or completely empty variables.; 26, expression_statement; 27, comment:# Create and mask the correlation matrix. Construct the base heatmap.; 28, expression_statement; 29, expression_statement; 30, expression_statement; 31, if_statement; 32, comment:# Apply visual corrections and modifications.; 33, expression_statement; 34, expression_statement; 35, expression_statement; 36, expression_statement; 37, expression_statement; 38, expression_statement; 39, expression_statement; 40, for_statement; 41, if_statement; 42, identifier:inline; 43, False; 44, identifier:filter; 45, None; 46, identifier:n; 47, integer:0; 48, identifier:p; 49, integer:0; 50, identifier:sort; 51, None; 52, identifier:figsize; 53, tuple; 54, identifier:fontsize; 55, integer:16; 56, identifier:labels; 57, True; 58, identifier:cmap; 59, string; 60, identifier:vmin; 61, unary_operator; 62, identifier:vmax; 63, integer:1; 64, identifier:cbar; 65, True; 66, comment:"""
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame.
Note that this visualization has no special support for large datasets. For those, try the dendrogram instead.
:param df: The DataFrame whose completeness is being heatmapped.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See
`nullity_filter()` for more information.
:param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for
more information.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for
more information.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See
`nullity_sort()` for more information.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12).
:param fontsize: The figure's font size.
:param labels: Whether or not to label each matrix entry with its correlation (default is True).
:param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`.
:param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale.
:param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""; 67, assignment; 68, assignment; 69, call; 70, assignment; 71, assignment; 72, assignment; 73, assignment; 74, assignment; 75, assignment; 76, identifier:labels; 77, block; 78, else_clause; 79, call; 80, call; 81, call; 82, call; 83, call; 84, call; 85, call; 86, identifier:text; 87, attribute; 88, block; 89, identifier:inline; 90, block; 91, else_clause; 92, integer:20; 93, integer:12; 94, string_content:RdBu; 95, integer:1; 96, identifier:df; 97, call; 98, identifier:df; 99, call; 100, attribute; 101, argument_list; 102, identifier:gs; 103, call; 104, identifier:ax0; 105, call; 106, identifier:df; 107, subscript; 108, identifier:corr_mat; 109, call; 110, identifier:mask; 111, call; 112, subscript; 113, True; 114, expression_statement; 115, block; 116, attribute; 117, argument_list; 118, attribute; 119, argument_list; 120, attribute; 121, argument_list; 122, attribute; 123, argument_list; 124, attribute; 125, argument_list; 126, attribute; 127, argument_list; 128, attribute; 129, argument_list; 130, identifier:ax0; 131, identifier:texts; 132, expression_statement; 133, if_statement; 134, expression_statement; 135, block; 136, identifier:nullity_filter; 137, argument_list; 138, identifier:nullity_sort; 139, argument_list; 140, identifier:plt; 141, identifier:figure; 142, keyword_argument; 143, attribute; 144, argument_list; 145, attribute; 146, argument_list; 147, attribute; 148, slice; 149, list_comprehension; 150, attribute; 151, argument_list; 152, attribute; 153, argument_list; 154, identifier:mask; 155, call; 156, call; 157, expression_statement; 158, attribute; 159, identifier:tick_bottom; 160, identifier:ax0; 161, identifier:set_xticklabels; 162, call; 163, keyword_argument; 164, keyword_argument; 165, keyword_argument; 166, identifier:ax0; 167, identifier:set_yticklabels; 168, call; 169, keyword_argument; 170, keyword_argument; 171, identifier:ax0; 172, identifier:set_yticklabels; 173, call; 174, keyword_argument; 175, keyword_argument; 176, attribute; 177, identifier:set_ticks_position; 178, string; 179, attribute; 180, identifier:set_ticks_position; 181, string; 182, attribute; 183, identifier:set_visible; 184, False; 185, assignment; 186, comparison_operator:0.95 <= t < 1; 187, block; 188, elif_clause; 189, elif_clause; 190, elif_clause; 191, elif_clause; 192, else_clause; 193, call; 194, return_statement; 195, identifier:df; 196, keyword_argument; 197, keyword_argument; 198, keyword_argument; 199, identifier:df; 200, keyword_argument; 201, identifier:figsize; 202, identifier:figsize; 203, identifier:gridspec; 204, identifier:GridSpec; 205, integer:1; 206, integer:1; 207, identifier:plt; 208, identifier:subplot; 209, subscript; 210, identifier:df; 211, identifier:iloc; 212, identifier:i; 213, for_in_clause; 214, if_clause; 215, call; 216, identifier:corr; 217, identifier:np; 218, identifier:zeros_like; 219, identifier:corr_mat; 220, attribute; 221, argument_list; 222, attribute; 223, argument_list; 224, call; 225, identifier:ax0; 226, identifier:xaxis; 227, attribute; 228, argument_list; 229, identifier:rotation; 230, integer:45; 231, identifier:ha; 232, string; 233, identifier:fontsize; 234, identifier:fontsize; 235, attribute; 236, argument_list; 237, identifier:fontsize; 238, identifier:fontsize; 239, identifier:rotation; 240, integer:0; 241, attribute; 242, argument_list; 243, identifier:rotation; 244, integer:0; 245, identifier:fontsize; 246, identifier:fontsize; 247, identifier:ax0; 248, identifier:xaxis; 249, string_content:none; 250, identifier:ax0; 251, identifier:yaxis; 252, string_content:none; 253, identifier:ax0; 254, identifier:patch; 255, identifier:t; 256, call; 257, float:0.95; 258, identifier:t; 259, integer:1; 260, expression_statement; 261, comparison_operator:-1 < t <= -0.95; 262, block; 263, comparison_operator:t == 1; 264, block; 265, comparison_operator:t == -1; 266, block; 267, comparison_operator:-0.05 < t < 0.05; 268, block; 269, block; 270, attribute; 271, argument_list; 272, identifier:ax0; 273, identifier:filter; 274, identifier:filter; 275, identifier:n; 276, identifier:n; 277, identifier:p; 278, identifier:p; 279, identifier:sort; 280, identifier:sort; 281, identifier:gs; 282, integer:0; 283, pattern_list; 284, call; 285, comparison_operator:n > 0; 286, attribute; 287, argument_list; 288, identifier:np; 289, identifier:triu_indices_from; 290, identifier:mask; 291, identifier:sns; 292, identifier:heatmap; 293, identifier:corr_mat; 294, keyword_argument; 295, keyword_argument; 296, keyword_argument; 297, keyword_argument; 298, keyword_argument; 299, keyword_argument; 300, keyword_argument; 301, keyword_argument; 302, attribute; 303, argument_list; 304, attribute; 305, identifier:get_majorticklabels; 306, string_content:right; 307, attribute; 308, identifier:get_majorticklabels; 309, attribute; 310, identifier:get_majorticklabels; 311, identifier:float; 312, argument_list; 313, call; 314, unary_operator; 315, identifier:t; 316, unary_operator; 317, expression_statement; 318, identifier:t; 319, integer:1; 320, expression_statement; 321, identifier:t; 322, unary_operator; 323, expression_statement; 324, unary_operator; 325, identifier:t; 326, float:0.05; 327, expression_statement; 328, expression_statement; 329, identifier:plt; 330, identifier:show; 331, identifier:i; 332, identifier:n; 333, identifier:enumerate; 334, argument_list; 335, identifier:n; 336, integer:0; 337, identifier:df; 338, identifier:isnull; 339, identifier:mask; 340, identifier:mask; 341, identifier:cmap; 342, identifier:cmap; 343, identifier:ax; 344, identifier:ax0; 345, identifier:cbar; 346, identifier:cbar; 347, identifier:annot; 348, True; 349, identifier:annot_kws; 350, dictionary; 351, identifier:vmin; 352, identifier:vmin; 353, identifier:vmax; 354, identifier:vmax; 355, identifier:sns; 356, identifier:heatmap; 357, identifier:corr_mat; 358, keyword_argument; 359, keyword_argument; 360, keyword_argument; 361, keyword_argument; 362, keyword_argument; 363, keyword_argument; 364, identifier:ax0; 365, identifier:xaxis; 366, identifier:ax0; 367, identifier:yaxis; 368, identifier:ax0; 369, identifier:yaxis; 370, call; 371, attribute; 372, argument_list; 373, integer:1; 374, float:0.95; 375, call; 376, call; 377, integer:1; 378, call; 379, float:0.05; 380, call; 381, call; 382, call; 383, pair; 384, identifier:mask; 385, identifier:mask; 386, identifier:cmap; 387, identifier:cmap; 388, identifier:ax; 389, identifier:ax0; 390, identifier:cbar; 391, identifier:cbar; 392, identifier:vmin; 393, identifier:vmin; 394, identifier:vmax; 395, identifier:vmax; 396, attribute; 397, argument_list; 398, identifier:text; 399, identifier:set_text; 400, string; 401, attribute; 402, argument_list; 403, attribute; 404, argument_list; 405, attribute; 406, argument_list; 407, attribute; 408, argument_list; 409, attribute; 410, argument_list; 411, attribute; 412, argument_list; 413, string; 414, binary_operator:fontsize - 2; 415, identifier:text; 416, identifier:get_text; 417, string_content:<1; 418, identifier:text; 419, identifier:set_text; 420, string; 421, identifier:text; 422, identifier:set_text; 423, string; 424, identifier:text; 425, identifier:set_text; 426, string; 427, identifier:text; 428, identifier:set_text; 429, string; 430, identifier:text; 431, identifier:set_text; 432, call; 433, identifier:np; 434, identifier:var; 435, call; 436, keyword_argument; 437, string_content:size; 438, identifier:fontsize; 439, integer:2; 440, string_content:>-1; 441, string_content:1; 442, string_content:-1; 443, identifier:round; 444, argument_list; 445, attribute; 446, argument_list; 447, identifier:axis; 448, string; 449, identifier:t; 450, integer:1; 451, identifier:df; 452, identifier:isnull; 453, string_content:rows | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 3, 14; 3, 15; 3, 16; 3, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 4, 30; 4, 31; 4, 32; 4, 33; 4, 34; 4, 35; 4, 36; 4, 37; 4, 38; 4, 39; 4, 40; 4, 41; 6, 42; 6, 43; 7, 44; 7, 45; 8, 46; 8, 47; 9, 48; 9, 49; 10, 50; 10, 51; 11, 52; 11, 53; 12, 54; 12, 55; 13, 56; 13, 57; 14, 58; 14, 59; 15, 60; 15, 61; 16, 62; 16, 63; 17, 64; 17, 65; 18, 66; 20, 67; 21, 68; 22, 69; 23, 70; 24, 71; 26, 72; 28, 73; 29, 74; 30, 75; 31, 76; 31, 77; 31, 78; 33, 79; 34, 80; 35, 81; 36, 82; 37, 83; 38, 84; 39, 85; 40, 86; 40, 87; 40, 88; 41, 89; 41, 90; 41, 91; 53, 92; 53, 93; 59, 94; 61, 95; 67, 96; 67, 97; 68, 98; 68, 99; 69, 100; 69, 101; 70, 102; 70, 103; 71, 104; 71, 105; 72, 106; 72, 107; 73, 108; 73, 109; 74, 110; 74, 111; 75, 112; 75, 113; 77, 114; 78, 115; 79, 116; 79, 117; 80, 118; 80, 119; 81, 120; 81, 121; 82, 122; 82, 123; 83, 124; 83, 125; 84, 126; 84, 127; 85, 128; 85, 129; 87, 130; 87, 131; 88, 132; 88, 133; 90, 134; 91, 135; 97, 136; 97, 137; 99, 138; 99, 139; 100, 140; 100, 141; 101, 142; 103, 143; 103, 144; 105, 145; 105, 146; 107, 147; 107, 148; 107, 149; 109, 150; 109, 151; 111, 152; 111, 153; 112, 154; 112, 155; 114, 156; 115, 157; 116, 158; 116, 159; 118, 160; 118, 161; 119, 162; 119, 163; 119, 164; 119, 165; 120, 166; 120, 167; 121, 168; 121, 169; 121, 170; 122, 171; 122, 172; 123, 173; 123, 174; 123, 175; 124, 176; 124, 177; 125, 178; 126, 179; 126, 180; 127, 181; 128, 182; 128, 183; 129, 184; 132, 185; 133, 186; 133, 187; 133, 188; 133, 189; 133, 190; 133, 191; 133, 192; 134, 193; 135, 194; 137, 195; 137, 196; 137, 197; 137, 198; 139, 199; 139, 200; 142, 201; 142, 202; 143, 203; 143, 204; 144, 205; 144, 206; 145, 207; 145, 208; 146, 209; 147, 210; 147, 211; 149, 212; 149, 213; 149, 214; 150, 215; 150, 216; 152, 217; 152, 218; 153, 219; 155, 220; 155, 221; 156, 222; 156, 223; 157, 224; 158, 225; 158, 226; 162, 227; 162, 228; 163, 229; 163, 230; 164, 231; 164, 232; 165, 233; 165, 234; 168, 235; 168, 236; 169, 237; 169, 238; 170, 239; 170, 240; 173, 241; 173, 242; 174, 243; 174, 244; 175, 245; 175, 246; 176, 247; 176, 248; 178, 249; 179, 250; 179, 251; 181, 252; 182, 253; 182, 254; 185, 255; 185, 256; 186, 257; 186, 258; 186, 259; 187, 260; 188, 261; 188, 262; 189, 263; 189, 264; 190, 265; 190, 266; 191, 267; 191, 268; 192, 269; 193, 270; 193, 271; 194, 272; 196, 273; 196, 274; 197, 275; 197, 276; 198, 277; 198, 278; 200, 279; 200, 280; 209, 281; 209, 282; 213, 283; 213, 284; 214, 285; 215, 286; 215, 287; 220, 288; 220, 289; 221, 290; 222, 291; 222, 292; 223, 293; 223, 294; 223, 295; 223, 296; 223, 297; 223, 298; 223, 299; 223, 300; 223, 301; 224, 302; 224, 303; 227, 304; 227, 305; 232, 306; 235, 307; 235, 308; 241, 309; 241, 310; 256, 311; 256, 312; 260, 313; 261, 314; 261, 315; 261, 316; 262, 317; 263, 318; 263, 319; 264, 320; 265, 321; 265, 322; 266, 323; 267, 324; 267, 325; 267, 326; 268, 327; 269, 328; 270, 329; 270, 330; 283, 331; 283, 332; 284, 333; 284, 334; 285, 335; 285, 336; 286, 337; 286, 338; 294, 339; 294, 340; 295, 341; 295, 342; 296, 343; 296, 344; 297, 345; 297, 346; 298, 347; 298, 348; 299, 349; 299, 350; 300, 351; 300, 352; 301, 353; 301, 354; 302, 355; 302, 356; 303, 357; 303, 358; 303, 359; 303, 360; 303, 361; 303, 362; 303, 363; 304, 364; 304, 365; 307, 366; 307, 367; 309, 368; 309, 369; 312, 370; 313, 371; 313, 372; 314, 373; 316, 374; 317, 375; 320, 376; 322, 377; 323, 378; 324, 379; 327, 380; 328, 381; 334, 382; 350, 383; 358, 384; 358, 385; 359, 386; 359, 387; 360, 388; 360, 389; 361, 390; 361, 391; 362, 392; 362, 393; 363, 394; 363, 395; 370, 396; 370, 397; 371, 398; 371, 399; 372, 400; 375, 401; 375, 402; 376, 403; 376, 404; 378, 405; 378, 406; 380, 407; 380, 408; 381, 409; 381, 410; 382, 411; 382, 412; 383, 413; 383, 414; 396, 415; 396, 416; 400, 417; 401, 418; 401, 419; 402, 420; 403, 421; 403, 422; 404, 423; 405, 424; 405, 425; 406, 426; 407, 427; 407, 428; 408, 429; 409, 430; 409, 431; 410, 432; 411, 433; 411, 434; 412, 435; 412, 436; 413, 437; 414, 438; 414, 439; 420, 440; 423, 441; 426, 442; 432, 443; 432, 444; 435, 445; 435, 446; 436, 447; 436, 448; 444, 449; 444, 450; 445, 451; 445, 452; 448, 453 | def heatmap(df, inline=False,
filter=None, n=0, p=0, sort=None,
figsize=(20, 12), fontsize=16, labels=True,
cmap='RdBu', vmin=-1, vmax=1, cbar=True
):
"""
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame.
Note that this visualization has no special support for large datasets. For those, try the dendrogram instead.
:param df: The DataFrame whose completeness is being heatmapped.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See
`nullity_filter()` for more information.
:param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for
more information.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for
more information.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See
`nullity_sort()` for more information.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12).
:param fontsize: The figure's font size.
:param labels: Whether or not to label each matrix entry with its correlation (default is True).
:param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`.
:param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale.
:param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
# Apply filters and sorts, set up the figure.
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
plt.figure(figsize=figsize)
gs = gridspec.GridSpec(1, 1)
ax0 = plt.subplot(gs[0])
# Remove completely filled or completely empty variables.
df = df.iloc[:,[i for i, n in enumerate(np.var(df.isnull(), axis='rows')) if n > 0]]
# Create and mask the correlation matrix. Construct the base heatmap.
corr_mat = df.isnull().corr()
mask = np.zeros_like(corr_mat)
mask[np.triu_indices_from(mask)] = True
if labels:
sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar,
annot=True, annot_kws={'size': fontsize - 2},
vmin=vmin, vmax=vmax)
else:
sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar,
vmin=vmin, vmax=vmax)
# Apply visual corrections and modifications.
ax0.xaxis.tick_bottom()
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right', fontsize=fontsize)
ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), fontsize=fontsize, rotation=0)
ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), rotation=0, fontsize=fontsize)
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.patch.set_visible(False)
for text in ax0.texts:
t = float(text.get_text())
if 0.95 <= t < 1:
text.set_text('<1')
elif -1 < t <= -0.95:
text.set_text('>-1')
elif t == 1:
text.set_text('1')
elif t == -1:
text.set_text('-1')
elif -0.05 < t < 0.05:
text.set_text('')
else:
text.set_text(round(t, 1))
if inline:
plt.show()
else:
return ax0 |
0, module; 1, function_definition; 2, function_name:dendrogram; 3, parameters; 4, block; 5, identifier:df; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, default_parameter; 14, default_parameter; 15, expression_statement; 16, if_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, expression_statement; 22, comment:# Link the hierarchical output matrix, figure out orientation, construct base dendrogram.; 23, expression_statement; 24, expression_statement; 25, if_statement; 26, expression_statement; 27, comment:# Remove extraneous default visual elements.; 28, expression_statement; 29, expression_statement; 30, if_statement; 31, expression_statement; 32, expression_statement; 33, expression_statement; 34, expression_statement; 35, expression_statement; 36, expression_statement; 37, expression_statement; 38, comment:# Set up the categorical axis labels and draw.; 39, if_statement; 40, if_statement; 41, if_statement; 42, identifier:method; 43, string; 44, identifier:filter; 45, None; 46, identifier:n; 47, integer:0; 48, identifier:p; 49, integer:0; 50, identifier:sort; 51, None; 52, identifier:orientation; 53, None; 54, identifier:figsize; 55, None; 56, identifier:fontsize; 57, integer:16; 58, identifier:inline; 59, False; 60, comment:"""
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as
a `scipy` dendrogram.
The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is
left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables.
:param df: The DataFrame whose completeness is being dendrogrammed.
:param method: The distance measure being used for clustering. This is a parameter that is passed to
`scipy.hierarchy`.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`.
:param fontsize: The figure's font size.
:param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50
columns and left-right if there are more.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""; 61, not_operator; 62, block; 63, call; 64, assignment; 65, assignment; 66, assignment; 67, assignment; 68, assignment; 69, assignment; 70, not_operator; 71, block; 72, call; 73, call; 74, call; 75, comparison_operator:orientation == 'bottom'; 76, block; 77, call; 78, call; 79, call; 80, call; 81, call; 82, call; 83, call; 84, comparison_operator:orientation == 'bottom'; 85, block; 86, elif_clause; 87, boolean_operator; 88, block; 89, else_clause; 90, identifier:inline; 91, block; 92, else_clause; 93, string_content:average; 94, identifier:figsize; 95, if_statement; 96, attribute; 97, argument_list; 98, identifier:gs; 99, call; 100, identifier:ax0; 101, call; 102, identifier:df; 103, call; 104, identifier:df; 105, call; 106, identifier:x; 107, call; 108, identifier:z; 109, call; 110, identifier:orientation; 111, if_statement; 112, attribute; 113, argument_list; 114, attribute; 115, argument_list; 116, attribute; 117, argument_list; 118, identifier:orientation; 119, string; 120, expression_statement; 121, attribute; 122, argument_list; 123, attribute; 124, argument_list; 125, attribute; 126, argument_list; 127, attribute; 128, argument_list; 129, attribute; 130, argument_list; 131, attribute; 132, argument_list; 133, attribute; 134, argument_list; 135, identifier:orientation; 136, string; 137, expression_statement; 138, comparison_operator:orientation == 'top'; 139, block; 140, comparison_operator:orientation == 'bottom'; 141, comparison_operator:orientation == 'top'; 142, expression_statement; 143, block; 144, expression_statement; 145, block; 146, boolean_operator; 147, block; 148, else_clause; 149, identifier:plt; 150, identifier:figure; 151, keyword_argument; 152, attribute; 153, argument_list; 154, attribute; 155, argument_list; 156, identifier:nullity_filter; 157, argument_list; 158, identifier:nullity_sort; 159, argument_list; 160, attribute; 161, argument_list; 162, attribute; 163, argument_list; 164, comparison_operator:len(df.columns) > 50; 165, block; 166, else_clause; 167, identifier:hierarchy; 168, identifier:dendrogram; 169, identifier:z; 170, keyword_argument; 171, keyword_argument; 172, keyword_argument; 173, keyword_argument; 174, keyword_argument; 175, keyword_argument; 176, identifier:ax0; 177, identifier:set_aspect; 178, string; 179, identifier:ax0; 180, identifier:grid; 181, keyword_argument; 182, string_content:bottom; 183, call; 184, attribute; 185, identifier:set_ticks_position; 186, string; 187, attribute; 188, identifier:set_ticks_position; 189, string; 190, subscript; 191, identifier:set_visible; 192, False; 193, subscript; 194, identifier:set_visible; 195, False; 196, subscript; 197, identifier:set_visible; 198, False; 199, subscript; 200, identifier:set_visible; 201, False; 202, attribute; 203, identifier:set_visible; 204, False; 205, string_content:bottom; 206, call; 207, identifier:orientation; 208, string; 209, expression_statement; 210, identifier:orientation; 211, string; 212, identifier:orientation; 213, string; 214, call; 215, expression_statement; 216, call; 217, return_statement; 218, boolean_operator; 219, comparison_operator:orientation == 'bottom'; 220, expression_statement; 221, block; 222, identifier:figsize; 223, identifier:figsize; 224, identifier:gridspec; 225, identifier:GridSpec; 226, integer:1; 227, integer:1; 228, identifier:plt; 229, identifier:subplot; 230, subscript; 231, identifier:df; 232, keyword_argument; 233, keyword_argument; 234, keyword_argument; 235, identifier:df; 236, keyword_argument; 237, identifier:np; 238, identifier:transpose; 239, attribute; 240, identifier:hierarchy; 241, identifier:linkage; 242, identifier:x; 243, identifier:method; 244, call; 245, integer:50; 246, expression_statement; 247, block; 248, identifier:orientation; 249, identifier:orientation; 250, identifier:labels; 251, call; 252, identifier:distance_sort; 253, string; 254, identifier:link_color_func; 255, lambda; 256, identifier:leaf_font_size; 257, identifier:fontsize; 258, identifier:ax; 259, identifier:ax0; 260, string_content:auto; 261, identifier:b; 262, False; 263, attribute; 264, argument_list; 265, identifier:ax0; 266, identifier:xaxis; 267, string_content:none; 268, identifier:ax0; 269, identifier:yaxis; 270, string_content:none; 271, attribute; 272, string; 273, attribute; 274, string; 275, attribute; 276, string; 277, attribute; 278, string; 279, identifier:ax0; 280, identifier:patch; 281, attribute; 282, argument_list; 283, string_content:top; 284, call; 285, string_content:bottom; 286, string_content:top; 287, attribute; 288, argument_list; 289, call; 290, attribute; 291, argument_list; 292, identifier:ax0; 293, comparison_operator:len(df.columns) <= 50; 294, comparison_operator:orientation == 'top'; 295, identifier:orientation; 296, string; 297, assignment; 298, expression_statement; 299, identifier:gs; 300, integer:0; 301, identifier:filter; 302, identifier:filter; 303, identifier:n; 304, identifier:n; 305, identifier:p; 306, identifier:p; 307, identifier:sort; 308, identifier:sort; 309, call; 310, identifier:values; 311, identifier:len; 312, argument_list; 313, assignment; 314, expression_statement; 315, attribute; 316, argument_list; 317, string_content:descending; 318, lambda_parameters; 319, string; 320, attribute; 321, identifier:tick_top; 322, identifier:ax0; 323, identifier:spines; 324, string_content:top; 325, identifier:ax0; 326, identifier:spines; 327, string_content:right; 328, identifier:ax0; 329, identifier:spines; 330, string_content:bottom; 331, identifier:ax0; 332, identifier:spines; 333, string_content:left; 334, identifier:ax0; 335, identifier:set_xticklabels; 336, call; 337, keyword_argument; 338, keyword_argument; 339, attribute; 340, argument_list; 341, identifier:ax0; 342, identifier:tick_params; 343, keyword_argument; 344, keyword_argument; 345, attribute; 346, argument_list; 347, identifier:plt; 348, identifier:show; 349, call; 350, integer:50; 351, identifier:orientation; 352, string; 353, string_content:bottom; 354, identifier:figsize; 355, tuple; 356, assignment; 357, attribute; 358, argument_list; 359, attribute; 360, identifier:orientation; 361, string; 362, assignment; 363, attribute; 364, identifier:tolist; 365, identifier:c; 366, string_content:black; 367, identifier:ax0; 368, identifier:xaxis; 369, attribute; 370, argument_list; 371, identifier:rotation; 372, integer:45; 373, identifier:ha; 374, string; 375, identifier:ax0; 376, identifier:set_xticklabels; 377, call; 378, keyword_argument; 379, keyword_argument; 380, identifier:axis; 381, string; 382, identifier:labelsize; 383, call; 384, identifier:ax0; 385, identifier:tick_params; 386, keyword_argument; 387, keyword_argument; 388, identifier:len; 389, argument_list; 390, string_content:top; 391, integer:25; 392, integer:10; 393, identifier:figsize; 394, tuple; 395, call; 396, identifier:astype; 397, identifier:int; 398, identifier:df; 399, identifier:columns; 400, string_content:left; 401, identifier:orientation; 402, string; 403, identifier:df; 404, identifier:columns; 405, attribute; 406, identifier:get_majorticklabels; 407, string_content:left; 408, attribute; 409, argument_list; 410, identifier:rotation; 411, integer:45; 412, identifier:ha; 413, string; 414, string_content:y; 415, identifier:int; 416, argument_list; 417, identifier:axis; 418, string; 419, identifier:labelsize; 420, call; 421, attribute; 422, integer:25; 423, binary_operator:(25 + len(df.columns) - 50)*0.5; 424, attribute; 425, argument_list; 426, string_content:bottom; 427, identifier:ax0; 428, identifier:xaxis; 429, attribute; 430, identifier:get_majorticklabels; 431, string_content:right; 432, binary_operator:fontsize / 16 * 20; 433, string_content:x; 434, identifier:int; 435, argument_list; 436, identifier:df; 437, identifier:columns; 438, parenthesized_expression; 439, float:0.5; 440, identifier:df; 441, identifier:isnull; 442, identifier:ax0; 443, identifier:xaxis; 444, binary_operator:fontsize / 16; 445, integer:20; 446, binary_operator:fontsize / 16 * 20; 447, binary_operator:25 + len(df.columns) - 50; 448, identifier:fontsize; 449, integer:16; 450, binary_operator:fontsize / 16; 451, integer:20; 452, binary_operator:25 + len(df.columns); 453, integer:50; 454, identifier:fontsize; 455, integer:16; 456, integer:25; 457, call; 458, identifier:len; 459, argument_list; 460, attribute; 461, identifier:df; 462, identifier:columns | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 3, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 4, 30; 4, 31; 4, 32; 4, 33; 4, 34; 4, 35; 4, 36; 4, 37; 4, 38; 4, 39; 4, 40; 4, 41; 6, 42; 6, 43; 7, 44; 7, 45; 8, 46; 8, 47; 9, 48; 9, 49; 10, 50; 10, 51; 11, 52; 11, 53; 12, 54; 12, 55; 13, 56; 13, 57; 14, 58; 14, 59; 15, 60; 16, 61; 16, 62; 17, 63; 18, 64; 19, 65; 20, 66; 21, 67; 23, 68; 24, 69; 25, 70; 25, 71; 26, 72; 28, 73; 29, 74; 30, 75; 30, 76; 31, 77; 32, 78; 33, 79; 34, 80; 35, 81; 36, 82; 37, 83; 39, 84; 39, 85; 39, 86; 40, 87; 40, 88; 40, 89; 41, 90; 41, 91; 41, 92; 43, 93; 61, 94; 62, 95; 63, 96; 63, 97; 64, 98; 64, 99; 65, 100; 65, 101; 66, 102; 66, 103; 67, 104; 67, 105; 68, 106; 68, 107; 69, 108; 69, 109; 70, 110; 71, 111; 72, 112; 72, 113; 73, 114; 73, 115; 74, 116; 74, 117; 75, 118; 75, 119; 76, 120; 77, 121; 77, 122; 78, 123; 78, 124; 79, 125; 79, 126; 80, 127; 80, 128; 81, 129; 81, 130; 82, 131; 82, 132; 83, 133; 83, 134; 84, 135; 84, 136; 85, 137; 86, 138; 86, 139; 87, 140; 87, 141; 88, 142; 89, 143; 91, 144; 92, 145; 95, 146; 95, 147; 95, 148; 96, 149; 96, 150; 97, 151; 99, 152; 99, 153; 101, 154; 101, 155; 103, 156; 103, 157; 105, 158; 105, 159; 107, 160; 107, 161; 109, 162; 109, 163; 111, 164; 111, 165; 111, 166; 112, 167; 112, 168; 113, 169; 113, 170; 113, 171; 113, 172; 113, 173; 113, 174; 113, 175; 114, 176; 114, 177; 115, 178; 116, 179; 116, 180; 117, 181; 119, 182; 120, 183; 121, 184; 121, 185; 122, 186; 123, 187; 123, 188; 124, 189; 125, 190; 125, 191; 126, 192; 127, 193; 127, 194; 128, 195; 129, 196; 129, 197; 130, 198; 131, 199; 131, 200; 132, 201; 133, 202; 133, 203; 134, 204; 136, 205; 137, 206; 138, 207; 138, 208; 139, 209; 140, 210; 140, 211; 141, 212; 141, 213; 142, 214; 143, 215; 144, 216; 145, 217; 146, 218; 146, 219; 147, 220; 148, 221; 151, 222; 151, 223; 152, 224; 152, 225; 153, 226; 153, 227; 154, 228; 154, 229; 155, 230; 157, 231; 157, 232; 157, 233; 157, 234; 159, 235; 159, 236; 160, 237; 160, 238; 161, 239; 162, 240; 162, 241; 163, 242; 163, 243; 164, 244; 164, 245; 165, 246; 166, 247; 170, 248; 170, 249; 171, 250; 171, 251; 172, 252; 172, 253; 173, 254; 173, 255; 174, 256; 174, 257; 175, 258; 175, 259; 178, 260; 181, 261; 181, 262; 183, 263; 183, 264; 184, 265; 184, 266; 186, 267; 187, 268; 187, 269; 189, 270; 190, 271; 190, 272; 193, 273; 193, 274; 196, 275; 196, 276; 199, 277; 199, 278; 202, 279; 202, 280; 206, 281; 206, 282; 208, 283; 209, 284; 211, 285; 213, 286; 214, 287; 214, 288; 215, 289; 216, 290; 216, 291; 217, 292; 218, 293; 218, 294; 219, 295; 219, 296; 220, 297; 221, 298; 230, 299; 230, 300; 232, 301; 232, 302; 233, 303; 233, 304; 234, 305; 234, 306; 236, 307; 236, 308; 239, 309; 239, 310; 244, 311; 244, 312; 246, 313; 247, 314; 251, 315; 251, 316; 253, 317; 255, 318; 255, 319; 263, 320; 263, 321; 271, 322; 271, 323; 272, 324; 273, 325; 273, 326; 274, 327; 275, 328; 275, 329; 276, 330; 277, 331; 277, 332; 278, 333; 281, 334; 281, 335; 282, 336; 282, 337; 282, 338; 284, 339; 284, 340; 287, 341; 287, 342; 288, 343; 288, 344; 289, 345; 289, 346; 290, 347; 290, 348; 293, 349; 293, 350; 294, 351; 294, 352; 296, 353; 297, 354; 297, 355; 298, 356; 309, 357; 309, 358; 312, 359; 313, 360; 313, 361; 314, 362; 315, 363; 315, 364; 318, 365; 319, 366; 320, 367; 320, 368; 336, 369; 336, 370; 337, 371; 337, 372; 338, 373; 338, 374; 339, 375; 339, 376; 340, 377; 340, 378; 340, 379; 343, 380; 343, 381; 344, 382; 344, 383; 345, 384; 345, 385; 346, 386; 346, 387; 349, 388; 349, 389; 352, 390; 355, 391; 355, 392; 356, 393; 356, 394; 357, 395; 357, 396; 358, 397; 359, 398; 359, 399; 361, 400; 362, 401; 362, 402; 363, 403; 363, 404; 369, 405; 369, 406; 374, 407; 377, 408; 377, 409; 378, 410; 378, 411; 379, 412; 379, 413; 381, 414; 383, 415; 383, 416; 386, 417; 386, 418; 387, 419; 387, 420; 389, 421; 394, 422; 394, 423; 395, 424; 395, 425; 402, 426; 405, 427; 405, 428; 408, 429; 408, 430; 413, 431; 416, 432; 418, 433; 420, 434; 420, 435; 421, 436; 421, 437; 423, 438; 423, 439; 424, 440; 424, 441; 429, 442; 429, 443; 432, 444; 432, 445; 435, 446; 438, 447; 444, 448; 444, 449; 446, 450; 446, 451; 447, 452; 447, 453; 450, 454; 450, 455; 452, 456; 452, 457; 457, 458; 457, 459; 459, 460; 460, 461; 460, 462 | def dendrogram(df, method='average',
filter=None, n=0, p=0, sort=None,
orientation=None, figsize=None,
fontsize=16, inline=False
):
"""
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as
a `scipy` dendrogram.
The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is
left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables.
:param df: The DataFrame whose completeness is being dendrogrammed.
:param method: The distance measure being used for clustering. This is a parameter that is passed to
`scipy.hierarchy`.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`.
:param fontsize: The figure's font size.
:param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50
columns and left-right if there are more.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
if not figsize:
if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom':
figsize = (25, 10)
else:
figsize = (25, (25 + len(df.columns) - 50)*0.5)
plt.figure(figsize=figsize)
gs = gridspec.GridSpec(1, 1)
ax0 = plt.subplot(gs[0])
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
# Link the hierarchical output matrix, figure out orientation, construct base dendrogram.
x = np.transpose(df.isnull().astype(int).values)
z = hierarchy.linkage(x, method)
if not orientation:
if len(df.columns) > 50:
orientation = 'left'
else:
orientation = 'bottom'
hierarchy.dendrogram(z,
orientation=orientation,
labels=df.columns.tolist(),
distance_sort='descending',
link_color_func=lambda c: 'black',
leaf_font_size=fontsize,
ax=ax0
)
# Remove extraneous default visual elements.
ax0.set_aspect('auto')
ax0.grid(b=False)
if orientation == 'bottom':
ax0.xaxis.tick_top()
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.spines['top'].set_visible(False)
ax0.spines['right'].set_visible(False)
ax0.spines['bottom'].set_visible(False)
ax0.spines['left'].set_visible(False)
ax0.patch.set_visible(False)
# Set up the categorical axis labels and draw.
if orientation == 'bottom':
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='left')
elif orientation == 'top':
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right')
if orientation == 'bottom' or orientation == 'top':
ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20))
else:
ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20))
if inline:
plt.show()
else:
return ax0 |
0, module; 1, function_definition; 2, function_name:nullity_sort; 3, parameters; 4, block; 5, identifier:df; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, identifier:sort; 10, None; 11, comment:"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
"""; 12, comparison_operator:sort == 'ascending'; 13, block; 14, elif_clause; 15, else_clause; 16, identifier:sort; 17, string; 18, return_statement; 19, comparison_operator:sort == 'descending'; 20, block; 21, block; 22, string_content:ascending; 23, subscript; 24, identifier:sort; 25, string; 26, return_statement; 27, return_statement; 28, attribute; 29, call; 30, slice; 31, string_content:descending; 32, subscript; 33, identifier:df; 34, identifier:df; 35, identifier:iloc; 36, attribute; 37, argument_list; 38, attribute; 39, call; 40, slice; 41, identifier:np; 42, identifier:argsort; 43, attribute; 44, identifier:df; 45, identifier:iloc; 46, attribute; 47, argument_list; 48, call; 49, identifier:values; 50, identifier:np; 51, identifier:flipud; 52, call; 53, attribute; 54, argument_list; 55, attribute; 56, argument_list; 57, identifier:df; 58, identifier:count; 59, keyword_argument; 60, identifier:np; 61, identifier:argsort; 62, attribute; 63, identifier:axis; 64, string; 65, call; 66, identifier:values; 67, string_content:columns; 68, attribute; 69, argument_list; 70, identifier:df; 71, identifier:count; 72, keyword_argument; 73, identifier:axis; 74, string; 75, string_content:columns | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 6, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 8, 15; 12, 16; 12, 17; 13, 18; 14, 19; 14, 20; 15, 21; 17, 22; 18, 23; 19, 24; 19, 25; 20, 26; 21, 27; 23, 28; 23, 29; 23, 30; 25, 31; 26, 32; 27, 33; 28, 34; 28, 35; 29, 36; 29, 37; 32, 38; 32, 39; 32, 40; 36, 41; 36, 42; 37, 43; 38, 44; 38, 45; 39, 46; 39, 47; 43, 48; 43, 49; 46, 50; 46, 51; 47, 52; 48, 53; 48, 54; 52, 55; 52, 56; 53, 57; 53, 58; 54, 59; 55, 60; 55, 61; 56, 62; 59, 63; 59, 64; 62, 65; 62, 66; 64, 67; 65, 68; 65, 69; 68, 70; 68, 71; 69, 72; 72, 73; 72, 74; 74, 75 | def nullity_sort(df, sort=None):
"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
"""
if sort == 'ascending':
return df.iloc[np.argsort(df.count(axis='columns').values), :]
elif sort == 'descending':
return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :]
else:
return df |
0, module; 1, function_definition; 2, function_name:sortino_ratio; 3, parameters; 4, block; 5, identifier:returns; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, expression_statement; 15, if_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, if_statement; 22, return_statement; 23, identifier:required_return; 24, integer:0; 25, identifier:period; 26, identifier:DAILY; 27, identifier:annualization; 28, None; 29, identifier:out; 30, None; 31, identifier:_downside_risk; 32, None; 33, comment:"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details.
"""; 34, assignment; 35, identifier:allocated_output; 36, block; 37, assignment; 38, comparison_operator:len(returns) < 2; 39, block; 40, assignment; 41, assignment; 42, assignment; 43, assignment; 44, call; 45, identifier:return_1d; 46, block; 47, elif_clause; 48, identifier:out; 49, identifier:allocated_output; 50, comparison_operator:out is None; 51, expression_statement; 52, identifier:return_1d; 53, comparison_operator:returns.ndim == 1; 54, call; 55, integer:2; 56, expression_statement; 57, if_statement; 58, return_statement; 59, identifier:adj_returns; 60, call; 61, identifier:ann_factor; 62, call; 63, identifier:average_annual_return; 64, binary_operator:nanmean(adj_returns, axis=0) * ann_factor; 65, identifier:annualized_downside_risk; 66, parenthesized_expression; 67, attribute; 68, argument_list; 69, expression_statement; 70, call; 71, block; 72, identifier:out; 73, None; 74, assignment; 75, attribute; 76, integer:1; 77, identifier:len; 78, argument_list; 79, assignment; 80, identifier:return_1d; 81, block; 82, identifier:out; 83, attribute; 84, argument_list; 85, identifier:annualization_factor; 86, argument_list; 87, call; 88, identifier:ann_factor; 89, conditional_expression:_downside_risk
if _downside_risk is not None else
downside_risk(returns, required_return, period, annualization); 90, identifier:np; 91, identifier:divide; 92, identifier:average_annual_return; 93, identifier:annualized_downside_risk; 94, keyword_argument; 95, assignment; 96, identifier:isinstance; 97, argument_list; 98, expression_statement; 99, identifier:out; 100, call; 101, identifier:returns; 102, identifier:ndim; 103, identifier:returns; 104, subscript; 105, attribute; 106, expression_statement; 107, identifier:np; 108, identifier:asanyarray; 109, call; 110, identifier:period; 111, identifier:annualization; 112, identifier:nanmean; 113, argument_list; 114, identifier:_downside_risk; 115, comparison_operator:_downside_risk is not None; 116, call; 117, identifier:out; 118, identifier:out; 119, identifier:out; 120, call; 121, identifier:returns; 122, attribute; 123, assignment; 124, attribute; 125, argument_list; 126, identifier:out; 127, tuple; 128, identifier:np; 129, identifier:nan; 130, assignment; 131, identifier:_adjust_returns; 132, argument_list; 133, identifier:adj_returns; 134, keyword_argument; 135, identifier:_downside_risk; 136, None; 137, identifier:downside_risk; 138, argument_list; 139, attribute; 140, argument_list; 141, identifier:pd; 142, identifier:DataFrame; 143, identifier:out; 144, call; 145, identifier:np; 146, identifier:empty; 147, subscript; 148, identifier:out; 149, call; 150, identifier:returns; 151, identifier:required_return; 152, identifier:axis; 153, integer:0; 154, identifier:returns; 155, identifier:required_return; 156, identifier:period; 157, identifier:annualization; 158, identifier:out; 159, identifier:item; 160, attribute; 161, argument_list; 162, attribute; 163, slice; 164, attribute; 165, argument_list; 166, identifier:pd; 167, identifier:Series; 168, identifier:out; 169, identifier:returns; 170, identifier:shape; 171, integer:1; 172, identifier:out; 173, identifier:item | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 6, 23; 6, 24; 7, 25; 7, 26; 8, 27; 8, 28; 9, 29; 9, 30; 10, 31; 10, 32; 11, 33; 12, 34; 13, 35; 13, 36; 14, 37; 15, 38; 15, 39; 16, 40; 17, 41; 18, 42; 19, 43; 20, 44; 21, 45; 21, 46; 21, 47; 22, 48; 34, 49; 34, 50; 36, 51; 37, 52; 37, 53; 38, 54; 38, 55; 39, 56; 39, 57; 39, 58; 40, 59; 40, 60; 41, 61; 41, 62; 42, 63; 42, 64; 43, 65; 43, 66; 44, 67; 44, 68; 46, 69; 47, 70; 47, 71; 50, 72; 50, 73; 51, 74; 53, 75; 53, 76; 54, 77; 54, 78; 56, 79; 57, 80; 57, 81; 58, 82; 60, 83; 60, 84; 62, 85; 62, 86; 64, 87; 64, 88; 66, 89; 67, 90; 67, 91; 68, 92; 68, 93; 68, 94; 69, 95; 70, 96; 70, 97; 71, 98; 74, 99; 74, 100; 75, 101; 75, 102; 78, 103; 79, 104; 79, 105; 81, 106; 83, 107; 83, 108; 84, 109; 86, 110; 86, 111; 87, 112; 87, 113; 89, 114; 89, 115; 89, 116; 94, 117; 94, 118; 95, 119; 95, 120; 97, 121; 97, 122; 98, 123; 100, 124; 100, 125; 104, 126; 104, 127; 105, 128; 105, 129; 106, 130; 109, 131; 109, 132; 113, 133; 113, 134; 115, 135; 115, 136; 116, 137; 116, 138; 120, 139; 120, 140; 122, 141; 122, 142; 123, 143; 123, 144; 124, 145; 124, 146; 125, 147; 130, 148; 130, 149; 132, 150; 132, 151; 134, 152; 134, 153; 138, 154; 138, 155; 138, 156; 138, 157; 139, 158; 139, 159; 144, 160; 144, 161; 147, 162; 147, 163; 149, 164; 149, 165; 160, 166; 160, 167; 161, 168; 162, 169; 162, 170; 163, 171; 164, 172; 164, 173 | def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
_downside_risk : float, optional
The downside risk of the given inputs, if known. Will be calculated if
not provided.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
sortino_ratio : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
return_1d = returns.ndim == 1
if len(returns) < 2:
out[()] = np.nan
if return_1d:
out = out.item()
return out
adj_returns = np.asanyarray(_adjust_returns(returns, required_return))
ann_factor = annualization_factor(period, annualization)
average_annual_return = nanmean(adj_returns, axis=0) * ann_factor
annualized_downside_risk = (
_downside_risk
if _downside_risk is not None else
downside_risk(returns, required_return, period, annualization)
)
np.divide(average_annual_return, annualized_downside_risk, out=out)
if return_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out)
return out |
0, module; 1, function_definition; 2, function_name:downside_risk; 3, parameters; 4, block; 5, identifier:returns; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, expression_statement; 12, if_statement; 13, expression_statement; 14, if_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, if_statement; 22, return_statement; 23, identifier:required_return; 24, integer:0; 25, identifier:period; 26, identifier:DAILY; 27, identifier:annualization; 28, None; 29, identifier:out; 30, None; 31, comment:"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct.
"""; 32, assignment; 33, identifier:allocated_output; 34, block; 35, assignment; 36, comparison_operator:len(returns) < 1; 37, block; 38, assignment; 39, assignment; 40, call; 41, call; 42, call; 43, call; 44, identifier:returns_1d; 45, block; 46, elif_clause; 47, identifier:out; 48, identifier:allocated_output; 49, comparison_operator:out is None; 50, expression_statement; 51, identifier:returns_1d; 52, comparison_operator:returns.ndim == 1; 53, call; 54, integer:1; 55, expression_statement; 56, if_statement; 57, return_statement; 58, identifier:ann_factor; 59, call; 60, identifier:downside_diff; 61, call; 62, attribute; 63, argument_list; 64, identifier:nanmean; 65, argument_list; 66, attribute; 67, argument_list; 68, attribute; 69, argument_list; 70, expression_statement; 71, call; 72, block; 73, identifier:out; 74, None; 75, assignment; 76, attribute; 77, integer:1; 78, identifier:len; 79, argument_list; 80, assignment; 81, identifier:returns_1d; 82, block; 83, identifier:out; 84, identifier:annualization_factor; 85, argument_list; 86, attribute; 87, argument_list; 88, identifier:np; 89, identifier:square; 90, identifier:downside_diff; 91, keyword_argument; 92, identifier:downside_diff; 93, keyword_argument; 94, keyword_argument; 95, identifier:np; 96, identifier:sqrt; 97, identifier:out; 98, keyword_argument; 99, identifier:np; 100, identifier:multiply; 101, identifier:out; 102, call; 103, keyword_argument; 104, assignment; 105, identifier:isinstance; 106, argument_list; 107, expression_statement; 108, identifier:out; 109, call; 110, identifier:returns; 111, identifier:ndim; 112, identifier:returns; 113, subscript; 114, attribute; 115, expression_statement; 116, identifier:period; 117, identifier:annualization; 118, identifier:np; 119, identifier:clip; 120, call; 121, attribute; 122, integer:0; 123, identifier:out; 124, identifier:downside_diff; 125, identifier:axis; 126, integer:0; 127, identifier:out; 128, identifier:out; 129, identifier:out; 130, identifier:out; 131, attribute; 132, argument_list; 133, identifier:out; 134, identifier:out; 135, identifier:out; 136, call; 137, identifier:returns; 138, attribute; 139, assignment; 140, attribute; 141, argument_list; 142, identifier:out; 143, tuple; 144, identifier:np; 145, identifier:nan; 146, assignment; 147, identifier:_adjust_returns; 148, argument_list; 149, identifier:np; 150, identifier:NINF; 151, identifier:np; 152, identifier:sqrt; 153, identifier:ann_factor; 154, attribute; 155, argument_list; 156, identifier:pd; 157, identifier:DataFrame; 158, identifier:out; 159, call; 160, identifier:np; 161, identifier:empty; 162, subscript; 163, identifier:out; 164, call; 165, call; 166, call; 167, identifier:out; 168, identifier:item; 169, attribute; 170, argument_list; 171, attribute; 172, slice; 173, attribute; 174, argument_list; 175, attribute; 176, argument_list; 177, attribute; 178, argument_list; 179, identifier:pd; 180, identifier:Series; 181, identifier:out; 182, keyword_argument; 183, identifier:returns; 184, identifier:shape; 185, integer:1; 186, identifier:out; 187, identifier:item; 188, identifier:np; 189, identifier:asanyarray; 190, identifier:returns; 191, identifier:np; 192, identifier:asanyarray; 193, identifier:required_return; 194, identifier:index; 195, attribute; 196, identifier:returns; 197, identifier:columns | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 6, 23; 6, 24; 7, 25; 7, 26; 8, 27; 8, 28; 9, 29; 9, 30; 10, 31; 11, 32; 12, 33; 12, 34; 13, 35; 14, 36; 14, 37; 15, 38; 16, 39; 17, 40; 18, 41; 19, 42; 20, 43; 21, 44; 21, 45; 21, 46; 22, 47; 32, 48; 32, 49; 34, 50; 35, 51; 35, 52; 36, 53; 36, 54; 37, 55; 37, 56; 37, 57; 38, 58; 38, 59; 39, 60; 39, 61; 40, 62; 40, 63; 41, 64; 41, 65; 42, 66; 42, 67; 43, 68; 43, 69; 45, 70; 46, 71; 46, 72; 49, 73; 49, 74; 50, 75; 52, 76; 52, 77; 53, 78; 53, 79; 55, 80; 56, 81; 56, 82; 57, 83; 59, 84; 59, 85; 61, 86; 61, 87; 62, 88; 62, 89; 63, 90; 63, 91; 65, 92; 65, 93; 65, 94; 66, 95; 66, 96; 67, 97; 67, 98; 68, 99; 68, 100; 69, 101; 69, 102; 69, 103; 70, 104; 71, 105; 71, 106; 72, 107; 75, 108; 75, 109; 76, 110; 76, 111; 79, 112; 80, 113; 80, 114; 82, 115; 85, 116; 85, 117; 86, 118; 86, 119; 87, 120; 87, 121; 87, 122; 91, 123; 91, 124; 93, 125; 93, 126; 94, 127; 94, 128; 98, 129; 98, 130; 102, 131; 102, 132; 103, 133; 103, 134; 104, 135; 104, 136; 106, 137; 106, 138; 107, 139; 109, 140; 109, 141; 113, 142; 113, 143; 114, 144; 114, 145; 115, 146; 120, 147; 120, 148; 121, 149; 121, 150; 131, 151; 131, 152; 132, 153; 136, 154; 136, 155; 138, 156; 138, 157; 139, 158; 139, 159; 140, 160; 140, 161; 141, 162; 146, 163; 146, 164; 148, 165; 148, 166; 154, 167; 154, 168; 159, 169; 159, 170; 162, 171; 162, 172; 164, 173; 164, 174; 165, 175; 165, 176; 166, 177; 166, 178; 169, 179; 169, 180; 170, 181; 170, 182; 171, 183; 171, 184; 172, 185; 173, 186; 173, 187; 175, 188; 175, 189; 176, 190; 177, 191; 177, 192; 178, 193; 182, 194; 182, 195; 195, 196; 195, 197 | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
"""
Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable return
period : str, optional
Defines the periodicity of the 'returns' data for purposes of
annualizing. Value ignored if `annualization` parameter is specified.
Defaults are::
'monthly':12
'weekly': 52
'daily': 252
annualization : int, optional
Used to suppress default values available in `period` to convert
returns into annual returns. Value should be the annual frequency of
`returns`.
out : array-like, optional
Array to use as output buffer.
If not passed, a new array will be created.
Returns
-------
downside_deviation : float or pd.Series
depends on input type
series ==> float
DataFrame ==> pd.Series
Note
-----
See `<https://www.sunrisecapital.com/wp-content/uploads/2014/06/Futures_
Mag_Sortino_0213.pdf>`__ for more details, specifically why using the
standard deviation of the negative returns is not correct.
"""
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(returns) < 1:
out[()] = np.nan
if returns_1d:
out = out.item()
return out
ann_factor = annualization_factor(period, annualization)
downside_diff = np.clip(
_adjust_returns(
np.asanyarray(returns),
np.asanyarray(required_return),
),
np.NINF,
0,
)
np.square(downside_diff, out=downside_diff)
nanmean(downside_diff, axis=0, out=out)
np.sqrt(out, out=out)
np.multiply(out, np.sqrt(ann_factor), out=out)
if returns_1d:
out = out.item()
elif isinstance(returns, pd.DataFrame):
out = pd.Series(out, index=returns.columns)
return out |
0, module; 1, function_definition; 2, function_name:GetLoadingOrder; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""Returns a list of filenames sorted by loading order.
Only includes files that Loader's standardized loading knows how to load"""; 11, assignment; 12, pattern_list; 13, call; 14, block; 15, call; 16, identifier:result; 17, dictionary; 18, identifier:filename; 19, identifier:mapping; 20, attribute; 21, argument_list; 22, expression_statement; 23, if_statement; 24, identifier:list; 25, generator_expression; 26, attribute; 27, identifier:iteritems; 28, assignment; 29, comparison_operator:loading_order is not None; 30, block; 31, subscript; 32, for_in_clause; 33, identifier:self; 34, identifier:_file_mapping; 35, identifier:loading_order; 36, subscript; 37, identifier:loading_order; 38, None; 39, expression_statement; 40, identifier:result; 41, identifier:key; 42, identifier:key; 43, call; 44, identifier:mapping; 45, string; 46, assignment; 47, identifier:sorted; 48, argument_list; 49, string_content:loading_order; 50, subscript; 51, identifier:filename; 52, identifier:result; 53, identifier:result; 54, identifier:loading_order | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 9, 15; 11, 16; 11, 17; 12, 18; 12, 19; 13, 20; 13, 21; 14, 22; 14, 23; 15, 24; 15, 25; 20, 26; 20, 27; 22, 28; 23, 29; 23, 30; 25, 31; 25, 32; 26, 33; 26, 34; 28, 35; 28, 36; 29, 37; 29, 38; 30, 39; 31, 40; 31, 41; 32, 42; 32, 43; 36, 44; 36, 45; 39, 46; 43, 47; 43, 48; 45, 49; 46, 50; 46, 51; 48, 52; 50, 53; 50, 54 | def GetLoadingOrder(self):
"""Returns a list of filenames sorted by loading order.
Only includes files that Loader's standardized loading knows how to load"""
result = {}
for filename, mapping in self._file_mapping.iteritems():
loading_order = mapping['loading_order']
if loading_order is not None:
result[loading_order] = filename
return list(result[key] for key in sorted(result)) |
0, module; 1, function_definition; 2, function_name:GetOrderKey; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, return_statement; 13, comment:"""Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values.
"""; 14, assignment; 15, call; 16, call; 17, assignment; 18, identifier:context_attribute; 19, identifier:context_attributes; 20, block; 21, identifier:tokens; 22, identifier:context_attributes; 23, list; 24, attribute; 25, argument_list; 26, attribute; 27, argument_list; 28, identifier:tokens; 29, list; 30, expression_statement; 31, string; 32, identifier:context_attributes; 33, identifier:extend; 34, attribute; 35, identifier:context_attributes; 36, identifier:extend; 37, call; 38, call; 39, string_content:_type; 40, identifier:ExceptionWithContext; 41, identifier:CONTEXT_PARTS; 42, attribute; 43, argument_list; 44, attribute; 45, argument_list; 46, identifier:self; 47, identifier:_GetExtraOrderAttributes; 48, identifier:tokens; 49, identifier:append; 50, call; 51, identifier:getattr; 52, argument_list; 53, identifier:self; 54, identifier:context_attribute; 55, None | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 6, 13; 7, 14; 8, 15; 9, 16; 10, 17; 11, 18; 11, 19; 11, 20; 12, 21; 14, 22; 14, 23; 15, 24; 15, 25; 16, 26; 16, 27; 17, 28; 17, 29; 20, 30; 23, 31; 24, 32; 24, 33; 25, 34; 26, 35; 26, 36; 27, 37; 30, 38; 31, 39; 34, 40; 34, 41; 37, 42; 37, 43; 38, 44; 38, 45; 42, 46; 42, 47; 44, 48; 44, 49; 45, 50; 50, 51; 50, 52; 52, 53; 52, 54; 52, 55 | def GetOrderKey(self):
"""Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values.
"""
context_attributes = ['_type']
context_attributes.extend(ExceptionWithContext.CONTEXT_PARTS)
context_attributes.extend(self._GetExtraOrderAttributes())
tokens = []
for context_attribute in context_attributes:
tokens.append(getattr(self, context_attribute, None))
return tokens |
0, module; 1, function_definition; 2, function_name:AddShapePointObjectUnsorted; 3, parameters; 4, block; 5, identifier:self; 6, identifier:shapepoint; 7, identifier:problems; 8, expression_statement; 9, if_statement; 10, if_statement; 11, if_statement; 12, if_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, comment:"""Insert a point into a correct position by sequence. """; 17, parenthesized_expression; 18, block; 19, elif_clause; 20, else_clause; 21, comparison_operator:shapepoint.shape_pt_sequence in self.sequence; 22, block; 23, boolean_operator; 24, block; 25, comparison_operator:shapepoint.shape_dist_traveled > self.max_distance; 26, block; 27, call; 28, call; 29, call; 30, boolean_operator; 31, expression_statement; 32, comparison_operator:shapepoint.shape_pt_sequence <= self.sequence[0]; 33, block; 34, block; 35, attribute; 36, attribute; 37, expression_statement; 38, comparison_operator:shapepoint.shape_dist_traveled is not None; 39, comparison_operator:len(self.sequence) > 0; 40, if_statement; 41, if_statement; 42, attribute; 43, attribute; 44, expression_statement; 45, attribute; 46, argument_list; 47, attribute; 48, argument_list; 49, attribute; 50, argument_list; 51, comparison_operator:len(self.sequence) == 0; 52, comparison_operator:shapepoint.shape_pt_sequence >= self.sequence[-1]; 53, assignment; 54, attribute; 55, subscript; 56, expression_statement; 57, expression_statement; 58, identifier:shapepoint; 59, identifier:shape_pt_sequence; 60, identifier:self; 61, identifier:sequence; 62, call; 63, attribute; 64, None; 65, call; 66, integer:0; 67, parenthesized_expression; 68, block; 69, parenthesized_expression; 70, block; 71, identifier:shapepoint; 72, identifier:shape_dist_traveled; 73, identifier:self; 74, identifier:max_distance; 75, assignment; 76, attribute; 77, identifier:insert; 78, identifier:index; 79, attribute; 80, attribute; 81, identifier:insert; 82, identifier:index; 83, attribute; 84, attribute; 85, identifier:insert; 86, identifier:index; 87, tuple; 88, call; 89, integer:0; 90, attribute; 91, subscript; 92, identifier:index; 93, call; 94, identifier:shapepoint; 95, identifier:shape_pt_sequence; 96, attribute; 97, integer:0; 98, assignment; 99, assignment; 100, attribute; 101, argument_list; 102, identifier:shapepoint; 103, identifier:shape_dist_traveled; 104, identifier:len; 105, argument_list; 106, boolean_operator; 107, expression_statement; 108, boolean_operator; 109, expression_statement; 110, attribute; 111, attribute; 112, identifier:self; 113, identifier:sequence; 114, identifier:shapepoint; 115, identifier:shape_pt_sequence; 116, identifier:self; 117, identifier:distance; 118, identifier:shapepoint; 119, identifier:shape_dist_traveled; 120, identifier:self; 121, identifier:points; 122, attribute; 123, attribute; 124, attribute; 125, identifier:len; 126, argument_list; 127, identifier:shapepoint; 128, identifier:shape_pt_sequence; 129, attribute; 130, unary_operator; 131, identifier:len; 132, argument_list; 133, identifier:self; 134, identifier:sequence; 135, identifier:index; 136, integer:0; 137, identifier:index; 138, call; 139, identifier:problems; 140, identifier:InvalidValue; 141, string; 142, attribute; 143, binary_operator:'The sequence number %d occurs more than once in '
'shape %s.' %
(shapepoint.shape_pt_sequence, self.shape_id); 144, attribute; 145, comparison_operator:index != len(self.sequence); 146, comparison_operator:shapepoint.shape_dist_traveled > self.distance[index]; 147, call; 148, comparison_operator:index > 0; 149, comparison_operator:shapepoint.shape_dist_traveled < self.distance[index - 1]; 150, call; 151, identifier:self; 152, identifier:max_distance; 153, identifier:shapepoint; 154, identifier:shape_dist_traveled; 155, identifier:shapepoint; 156, identifier:shape_pt_lat; 157, identifier:shapepoint; 158, identifier:shape_pt_lon; 159, identifier:shapepoint; 160, identifier:shape_dist_traveled; 161, attribute; 162, identifier:self; 163, identifier:sequence; 164, integer:1; 165, attribute; 166, attribute; 167, argument_list; 168, string_content:shape_pt_sequence; 169, identifier:shapepoint; 170, identifier:shape_pt_sequence; 171, concatenated_string; 172, tuple; 173, identifier:self; 174, identifier:sequence; 175, identifier:index; 176, call; 177, attribute; 178, subscript; 179, attribute; 180, argument_list; 181, identifier:index; 182, integer:0; 183, attribute; 184, subscript; 185, attribute; 186, argument_list; 187, identifier:self; 188, identifier:sequence; 189, identifier:self; 190, identifier:sequence; 191, identifier:bisect; 192, identifier:bisect; 193, attribute; 194, attribute; 195, string; 196, string; 197, attribute; 198, attribute; 199, identifier:len; 200, argument_list; 201, identifier:shapepoint; 202, identifier:shape_dist_traveled; 203, attribute; 204, identifier:index; 205, identifier:problems; 206, identifier:InvalidValue; 207, string; 208, attribute; 209, binary_operator:'Each subsequent point in a shape should have '
'a distance value that shouldn\'t be larger '
'than the next ones. In this case, the next '
'distance was %f.' % self.distance[index]; 210, identifier:shapepoint; 211, identifier:shape_dist_traveled; 212, attribute; 213, binary_operator:index - 1; 214, identifier:problems; 215, identifier:InvalidValue; 216, string; 217, attribute; 218, binary_operator:'Each subsequent point in a shape should have '
'a distance value that\'s at least as large as '
'the previous ones. In this case, the previous '
'distance was %f.' % self.distance[index - 1]; 219, identifier:self; 220, identifier:sequence; 221, identifier:shapepoint; 222, identifier:shape_pt_sequence; 223, string_content:The sequence number %d occurs more than once in; 224, string_content:shape %s.; 225, identifier:shapepoint; 226, identifier:shape_pt_sequence; 227, identifier:self; 228, identifier:shape_id; 229, attribute; 230, identifier:self; 231, identifier:distance; 232, string_content:shape_dist_traveled; 233, identifier:shapepoint; 234, identifier:shape_dist_traveled; 235, concatenated_string; 236, subscript; 237, identifier:self; 238, identifier:distance; 239, identifier:index; 240, integer:1; 241, string_content:shape_dist_traveled; 242, identifier:shapepoint; 243, identifier:shape_dist_traveled; 244, concatenated_string; 245, subscript; 246, identifier:self; 247, identifier:sequence; 248, string; 249, string; 250, string; 251, string; 252, attribute; 253, identifier:index; 254, string; 255, string; 256, string; 257, string; 258, attribute; 259, binary_operator:index - 1; 260, string_content:Each subsequent point in a shape should have; 261, string_content; 262, string_content:than the next ones. In this case, the next; 263, string_content:distance was %f.; 264, identifier:self; 265, identifier:distance; 266, string_content:Each subsequent point in a shape should have; 267, string_content; 268, string_content:the previous ones. In this case, the previous; 269, string_content:distance was %f.; 270, identifier:self; 271, identifier:distance; 272, identifier:index; 273, integer:1; 274, escape_sequence:\'; 275, escape_sequence:\' | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 8, 16; 9, 17; 9, 18; 9, 19; 9, 20; 10, 21; 10, 22; 11, 23; 11, 24; 12, 25; 12, 26; 13, 27; 14, 28; 15, 29; 17, 30; 18, 31; 19, 32; 19, 33; 20, 34; 21, 35; 21, 36; 22, 37; 23, 38; 23, 39; 24, 40; 24, 41; 25, 42; 25, 43; 26, 44; 27, 45; 27, 46; 28, 47; 28, 48; 29, 49; 29, 50; 30, 51; 30, 52; 31, 53; 32, 54; 32, 55; 33, 56; 34, 57; 35, 58; 35, 59; 36, 60; 36, 61; 37, 62; 38, 63; 38, 64; 39, 65; 39, 66; 40, 67; 40, 68; 41, 69; 41, 70; 42, 71; 42, 72; 43, 73; 43, 74; 44, 75; 45, 76; 45, 77; 46, 78; 46, 79; 47, 80; 47, 81; 48, 82; 48, 83; 49, 84; 49, 85; 50, 86; 50, 87; 51, 88; 51, 89; 52, 90; 52, 91; 53, 92; 53, 93; 54, 94; 54, 95; 55, 96; 55, 97; 56, 98; 57, 99; 62, 100; 62, 101; 63, 102; 63, 103; 65, 104; 65, 105; 67, 106; 68, 107; 69, 108; 70, 109; 75, 110; 75, 111; 76, 112; 76, 113; 79, 114; 79, 115; 80, 116; 80, 117; 83, 118; 83, 119; 84, 120; 84, 121; 87, 122; 87, 123; 87, 124; 88, 125; 88, 126; 90, 127; 90, 128; 91, 129; 91, 130; 93, 131; 93, 132; 96, 133; 96, 134; 98, 135; 98, 136; 99, 137; 99, 138; 100, 139; 100, 140; 101, 141; 101, 142; 101, 143; 105, 144; 106, 145; 106, 146; 107, 147; 108, 148; 108, 149; 109, 150; 110, 151; 110, 152; 111, 153; 111, 154; 122, 155; 122, 156; 123, 157; 123, 158; 124, 159; 124, 160; 126, 161; 129, 162; 129, 163; 130, 164; 132, 165; 138, 166; 138, 167; 141, 168; 142, 169; 142, 170; 143, 171; 143, 172; 144, 173; 144, 174; 145, 175; 145, 176; 146, 177; 146, 178; 147, 179; 147, 180; 148, 181; 148, 182; 149, 183; 149, 184; 150, 185; 150, 186; 161, 187; 161, 188; 165, 189; 165, 190; 166, 191; 166, 192; 167, 193; 167, 194; 171, 195; 171, 196; 172, 197; 172, 198; 176, 199; 176, 200; 177, 201; 177, 202; 178, 203; 178, 204; 179, 205; 179, 206; 180, 207; 180, 208; 180, 209; 183, 210; 183, 211; 184, 212; 184, 213; 185, 214; 185, 215; 186, 216; 186, 217; 186, 218; 193, 219; 193, 220; 194, 221; 194, 222; 195, 223; 196, 224; 197, 225; 197, 226; 198, 227; 198, 228; 200, 229; 203, 230; 203, 231; 207, 232; 208, 233; 208, 234; 209, 235; 209, 236; 212, 237; 212, 238; 213, 239; 213, 240; 216, 241; 217, 242; 217, 243; 218, 244; 218, 245; 229, 246; 229, 247; 235, 248; 235, 249; 235, 250; 235, 251; 236, 252; 236, 253; 244, 254; 244, 255; 244, 256; 244, 257; 245, 258; 245, 259; 248, 260; 249, 261; 250, 262; 251, 263; 252, 264; 252, 265; 254, 266; 255, 267; 256, 268; 257, 269; 258, 270; 258, 271; 259, 272; 259, 273; 261, 274; 267, 275 | def AddShapePointObjectUnsorted(self, shapepoint, problems):
"""Insert a point into a correct position by sequence. """
if (len(self.sequence) == 0 or
shapepoint.shape_pt_sequence >= self.sequence[-1]):
index = len(self.sequence)
elif shapepoint.shape_pt_sequence <= self.sequence[0]:
index = 0
else:
index = bisect.bisect(self.sequence, shapepoint.shape_pt_sequence)
if shapepoint.shape_pt_sequence in self.sequence:
problems.InvalidValue('shape_pt_sequence', shapepoint.shape_pt_sequence,
'The sequence number %d occurs more than once in '
'shape %s.' %
(shapepoint.shape_pt_sequence, self.shape_id))
if shapepoint.shape_dist_traveled is not None and len(self.sequence) > 0:
if (index != len(self.sequence) and
shapepoint.shape_dist_traveled > self.distance[index]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that shouldn\'t be larger '
'than the next ones. In this case, the next '
'distance was %f.' % self.distance[index])
if (index > 0 and
shapepoint.shape_dist_traveled < self.distance[index - 1]):
problems.InvalidValue('shape_dist_traveled',
shapepoint.shape_dist_traveled,
'Each subsequent point in a shape should have '
'a distance value that\'s at least as large as '
'the previous ones. In this case, the previous '
'distance was %f.' % self.distance[index - 1])
if shapepoint.shape_dist_traveled > self.max_distance:
self.max_distance = shapepoint.shape_dist_traveled
self.sequence.insert(index, shapepoint.shape_pt_sequence)
self.distance.insert(index, shapepoint.shape_dist_traveled)
self.points.insert(index, (shapepoint.shape_pt_lat,
shapepoint.shape_pt_lon,
shapepoint.shape_dist_traveled)) |
0, module; 1, function_definition; 2, function_name:GetStopTimes; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, expression_statement; 8, comment:# In theory problems=None should be safe because data from database has been; 9, comment:# validated. See comment in _LoadStopTimes for why this isn't always true.; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, if_statement; 15, for_statement; 16, return_statement; 17, identifier:problems; 18, None; 19, comment:"""Return a sorted list of StopTime objects for this trip."""; 20, assignment; 21, call; 22, assignment; 23, assignment; 24, comparison_operator:problems is None; 25, comment:# TODO: delete this branch when StopTime.__init__ doesn't need a; 26, comment:# ProblemReporter; 27, block; 28, identifier:row; 29, call; 30, block; 31, identifier:stop_times; 32, identifier:cursor; 33, call; 34, attribute; 35, argument_list; 36, identifier:stop_times; 37, list; 38, identifier:stoptime_class; 39, attribute; 40, identifier:problems; 41, None; 42, expression_statement; 43, attribute; 44, argument_list; 45, expression_statement; 46, expression_statement; 47, attribute; 48, argument_list; 49, identifier:cursor; 50, identifier:execute; 51, concatenated_string; 52, tuple; 53, call; 54, identifier:StopTime; 55, assignment; 56, identifier:cursor; 57, identifier:fetchall; 58, assignment; 59, call; 60, attribute; 61, identifier:cursor; 62, string; 63, string; 64, string; 65, string; 66, string; 67, attribute; 68, attribute; 69, argument_list; 70, identifier:problems; 71, attribute; 72, identifier:stop; 73, call; 74, attribute; 75, argument_list; 76, attribute; 77, identifier:_connection; 78, string_content:SELECT arrival_secs,departure_secs,stop_headsign,pickup_type,; 79, string_content:drop_off_type,shape_dist_traveled,stop_id,stop_sequence,timepoint; 80, string_content:FROM stop_times; 81, string_content:WHERE trip_id=?; 82, string_content:ORDER BY stop_sequence; 83, identifier:self; 84, identifier:trip_id; 85, identifier:self; 86, identifier:GetGtfsFactory; 87, identifier:problems_module; 88, identifier:default_problem_reporter; 89, attribute; 90, argument_list; 91, identifier:stop_times; 92, identifier:append; 93, call; 94, identifier:self; 95, identifier:_schedule; 96, attribute; 97, identifier:GetStop; 98, subscript; 99, identifier:stoptime_class; 100, argument_list; 101, identifier:self; 102, identifier:_schedule; 103, identifier:row; 104, integer:6; 105, keyword_argument; 106, keyword_argument; 107, keyword_argument; 108, keyword_argument; 109, keyword_argument; 110, keyword_argument; 111, keyword_argument; 112, keyword_argument; 113, keyword_argument; 114, keyword_argument; 115, identifier:problems; 116, identifier:problems; 117, identifier:stop; 118, identifier:stop; 119, identifier:arrival_secs; 120, subscript; 121, identifier:departure_secs; 122, subscript; 123, identifier:stop_headsign; 124, subscript; 125, identifier:pickup_type; 126, subscript; 127, identifier:drop_off_type; 128, subscript; 129, identifier:shape_dist_traveled; 130, subscript; 131, identifier:stop_sequence; 132, subscript; 133, identifier:timepoint; 134, subscript; 135, identifier:row; 136, integer:0; 137, identifier:row; 138, integer:1; 139, identifier:row; 140, integer:2; 141, identifier:row; 142, integer:3; 143, identifier:row; 144, integer:4; 145, identifier:row; 146, integer:5; 147, identifier:row; 148, integer:7; 149, identifier:row; 150, integer:8 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 6, 17; 6, 18; 7, 19; 10, 20; 11, 21; 12, 22; 13, 23; 14, 24; 14, 25; 14, 26; 14, 27; 15, 28; 15, 29; 15, 30; 16, 31; 20, 32; 20, 33; 21, 34; 21, 35; 22, 36; 22, 37; 23, 38; 23, 39; 24, 40; 24, 41; 27, 42; 29, 43; 29, 44; 30, 45; 30, 46; 33, 47; 33, 48; 34, 49; 34, 50; 35, 51; 35, 52; 39, 53; 39, 54; 42, 55; 43, 56; 43, 57; 45, 58; 46, 59; 47, 60; 47, 61; 51, 62; 51, 63; 51, 64; 51, 65; 51, 66; 52, 67; 53, 68; 53, 69; 55, 70; 55, 71; 58, 72; 58, 73; 59, 74; 59, 75; 60, 76; 60, 77; 62, 78; 63, 79; 64, 80; 65, 81; 66, 82; 67, 83; 67, 84; 68, 85; 68, 86; 71, 87; 71, 88; 73, 89; 73, 90; 74, 91; 74, 92; 75, 93; 76, 94; 76, 95; 89, 96; 89, 97; 90, 98; 93, 99; 93, 100; 96, 101; 96, 102; 98, 103; 98, 104; 100, 105; 100, 106; 100, 107; 100, 108; 100, 109; 100, 110; 100, 111; 100, 112; 100, 113; 100, 114; 105, 115; 105, 116; 106, 117; 106, 118; 107, 119; 107, 120; 108, 121; 108, 122; 109, 123; 109, 124; 110, 125; 110, 126; 111, 127; 111, 128; 112, 129; 112, 130; 113, 131; 113, 132; 114, 133; 114, 134; 120, 135; 120, 136; 122, 137; 122, 138; 124, 139; 124, 140; 126, 141; 126, 142; 128, 143; 128, 144; 130, 145; 130, 146; 132, 147; 132, 148; 134, 149; 134, 150 | def GetStopTimes(self, problems=None):
"""Return a sorted list of StopTime objects for this trip."""
# In theory problems=None should be safe because data from database has been
# validated. See comment in _LoadStopTimes for why this isn't always true.
cursor = self._schedule._connection.cursor()
cursor.execute(
'SELECT arrival_secs,departure_secs,stop_headsign,pickup_type,'
'drop_off_type,shape_dist_traveled,stop_id,stop_sequence,timepoint '
'FROM stop_times '
'WHERE trip_id=? '
'ORDER BY stop_sequence', (self.trip_id,))
stop_times = []
stoptime_class = self.GetGtfsFactory().StopTime
if problems is None:
# TODO: delete this branch when StopTime.__init__ doesn't need a
# ProblemReporter
problems = problems_module.default_problem_reporter
for row in cursor.fetchall():
stop = self._schedule.GetStop(row[6])
stop_times.append(stoptime_class(problems=problems,
stop=stop,
arrival_secs=row[0],
departure_secs=row[1],
stop_headsign=row[2],
pickup_type=row[3],
drop_off_type=row[4],
shape_dist_traveled=row[5],
stop_sequence=row[7],
timepoint=row[8]))
return stop_times |
0, module; 1, function_definition; 2, function_name:GetFrequencyStartTimes; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, comment:# for each headway period of the trip; 9, for_statement; 10, return_statement; 11, comment:"""Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list."""; 12, assignment; 13, identifier:freq_tuple; 14, call; 15, block; 16, identifier:start_times; 17, identifier:start_times; 18, list; 19, attribute; 20, argument_list; 21, expression_statement; 22, comment:# reset run secs to the start of the timeframe; 23, expression_statement; 24, while_statement; 25, identifier:self; 26, identifier:GetFrequencyTuples; 27, assignment; 28, assignment; 29, comparison_operator:run_secs < end_secs; 30, block; 31, tuple_pattern; 32, subscript; 33, identifier:run_secs; 34, identifier:start_secs; 35, identifier:run_secs; 36, identifier:end_secs; 37, expression_statement; 38, comment:# increment current run secs by headway secs; 39, expression_statement; 40, identifier:start_secs; 41, identifier:end_secs; 42, identifier:headway_secs; 43, identifier:freq_tuple; 44, slice; 45, call; 46, augmented_assignment; 47, integer:0; 48, integer:3; 49, attribute; 50, argument_list; 51, identifier:run_secs; 52, identifier:headway_secs; 53, identifier:start_times; 54, identifier:append; 55, identifier:run_secs | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 9, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 14, 19; 14, 20; 15, 21; 15, 22; 15, 23; 15, 24; 19, 25; 19, 26; 21, 27; 23, 28; 24, 29; 24, 30; 27, 31; 27, 32; 28, 33; 28, 34; 29, 35; 29, 36; 30, 37; 30, 38; 30, 39; 31, 40; 31, 41; 31, 42; 32, 43; 32, 44; 37, 45; 39, 46; 44, 47; 44, 48; 45, 49; 45, 50; 46, 51; 46, 52; 49, 53; 49, 54; 50, 55 | def GetFrequencyStartTimes(self):
"""Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list."""
start_times = []
# for each headway period of the trip
for freq_tuple in self.GetFrequencyTuples():
(start_secs, end_secs, headway_secs) = freq_tuple[0:3]
# reset run secs to the start of the timeframe
run_secs = start_secs
while run_secs < end_secs:
start_times.append(run_secs)
# increment current run secs by headway secs
run_secs += headway_secs
return start_times |
0, module; 1, function_definition; 2, function_name:create; 3, parameters; 4, block; 5, identifier:filename; 6, identifier:spec; 7, expression_statement; 8, import_from_statement; 9, if_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, if_statement; 15, if_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, if_statement; 21, expression_statement; 22, if_statement; 23, expression_statement; 24, return_statement; 25, comment:"""Create a new segy file.
Create a new segy file with the geometry and properties given by `spec`.
This enables creating SEGY files from your data. The created file supports
all segyio modes, but has an emphasis on writing. The spec must be
complete, otherwise an exception will be raised. A default, empty spec can
be created with ``segyio.spec()``.
Very little data is written to the file, so just calling create is not
sufficient to re-read the file with segyio. Rather, every trace header and
trace must be written to the file to be considered complete.
Create should be used together with python's ``with`` statement. This ensure
the data is written. Please refer to the examples.
The ``segyio.spec()`` function will default sorting, offsets and everything
in the mandatory group, except format and samples, and requires the caller
to fill in *all* the fields in either of the exclusive groups.
If any field is missing from the first exclusive group, and the tracecount
is set, the resulting file will be considered unstructured. If the
tracecount is set, and all fields of the first exclusive group are
specified, the file is considered structured and the tracecount is inferred
from the xlines/ilines/offsets. The offsets are defaulted to ``[1]`` by
``segyio.spec()``.
Parameters
----------
filename : str
Path to file to create
spec : segyio.spec
Structure of the segy file
Returns
-------
file : segyio.SegyFile
An open segyio file handle, similar to that returned by `segyio.open`
See also
--------
segyio.spec : template for the `spec` argument
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.4
Support for creating unstructured files
.. versionchanged:: 1.8
Support for creating lsb files
The ``spec`` is any object that has the following attributes
Mandatory::
iline : int or segyio.BinField
xline : int or segyio.BinField
samples : array of int
format : { 1, 5 }
1 = IBM float, 5 = IEEE float
Exclusive::
ilines : array_like of int
xlines : array_like of int
offsets : array_like of int
sorting : int or segyio.TraceSortingFormat
OR
tracecount : int
Optional::
ext_headers : int
endian : str { 'big', 'msb', 'little', 'lsb' }
defaults to 'big'
Examples
--------
Create a file:
>>> spec = segyio.spec()
>>> spec.ilines = [1, 2, 3, 4]
>>> spec.xlines = [11, 12, 13]
>>> spec.samples = list(range(50))
>>> spec.sorting = 2
>>> spec.format = 1
>>> with segyio.create(path, spec) as f:
... ## fill the file with data
... pass
...
Copy a file, but shorten all traces by 50 samples:
>>> with segyio.open(srcpath) as src:
... spec = segyio.spec()
... spec.sorting = src.sorting
... spec.format = src.format
... spec.samples = src.samples[:len(src.samples) - 50]
... spec.ilines = src.ilines
... spec.xline = src.xlines
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.trace = src.trace
Copy a file, but shift samples time by 50:
>>> with segyio.open(srcpath) as src:
... delrt = 50
... spec = segyio.spec()
... spec.samples = src.samples + delrt
... spec.ilines = src.ilines
... spec.xline = src.xlines
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.header = { TraceField.DelayRecordingTime: delrt }
... dst.trace = src.trace
Copy a file, but shorten all traces by 50 samples (since v1.4):
>>> with segyio.open(srcpath) as src:
... spec = segyio.tools.metadata(src)
... spec.samples = spec.samples[:len(spec.samples) - 50]
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.trace = src.trace
"""; 26, relative_import; 27, dotted_name; 28, not_operator; 29, block; 30, else_clause; 31, assignment; 32, assignment; 33, assignment; 34, assignment; 35, comparison_operator:endian is None; 36, block; 37, comparison_operator:endian not in endians; 38, block; 39, assignment; 40, call; 41, assignment; 42, assignment; 43, call; 44, block; 45, assignment; 46, comparison_operator:len(samples) == 1; 47, block; 48, else_clause; 49, call; 50, identifier:f; 51, import_prefix; 52, identifier:_segyio; 53, call; 54, expression_statement; 55, block; 56, identifier:ext_headers; 57, conditional_expression:spec.ext_headers if hasattr(spec, 'ext_headers') else 0; 58, identifier:samples; 59, call; 60, identifier:endians; 61, dictionary; 62, identifier:endian; 63, conditional_expression:spec.endian if hasattr(spec, 'endian') else 'big'; 64, identifier:endian; 65, None; 66, expression_statement; 67, identifier:endian; 68, identifier:endians; 69, expression_statement; 70, expression_statement; 71, raise_statement; 72, identifier:fd; 73, call; 74, attribute; 75, argument_list; 76, identifier:f; 77, call; 78, attribute; 79, identifier:samples; 80, identifier:structured; 81, argument_list; 82, expression_statement; 83, if_statement; 84, expression_statement; 85, subscript; 86, call; 87, call; 88, integer:1; 89, expression_statement; 90, block; 91, attribute; 92, argument_list; 93, identifier:structured; 94, argument_list; 95, assignment; 96, expression_statement; 97, attribute; 98, call; 99, integer:0; 100, attribute; 101, argument_list; 102, pair; 103, comment:# (1 << 8); 104, pair; 105, pair; 106, pair; 107, attribute; 108, call; 109, string; 110, assignment; 111, assignment; 112, assignment; 113, call; 114, attribute; 115, argument_list; 116, identifier:fd; 117, identifier:segymake; 118, keyword_argument; 119, keyword_argument; 120, keyword_argument; 121, keyword_argument; 122, attribute; 123, argument_list; 124, identifier:f; 125, identifier:_samples; 126, identifier:spec; 127, assignment; 128, comparison_operator:sorting is None; 129, block; 130, call; 131, attribute; 132, integer:0; 133, identifier:default_text_header; 134, argument_list; 135, identifier:len; 136, argument_list; 137, assignment; 138, expression_statement; 139, attribute; 140, identifier:update; 141, keyword_argument; 142, keyword_argument; 143, keyword_argument; 144, keyword_argument; 145, keyword_argument; 146, keyword_argument; 147, keyword_argument; 148, keyword_argument; 149, identifier:spec; 150, identifier:tracecount; 151, attribute; 152, assignment; 153, identifier:spec; 154, identifier:ext_headers; 155, identifier:hasattr; 156, argument_list; 157, identifier:numpy; 158, identifier:asarray; 159, attribute; 160, string; 161, integer:256; 162, string; 163, integer:256; 164, string; 165, integer:0; 166, string; 167, integer:0; 168, identifier:spec; 169, identifier:endian; 170, identifier:hasattr; 171, argument_list; 172, string_content:big; 173, identifier:endian; 174, string; 175, identifier:problem; 176, string; 177, identifier:opts; 178, call; 179, identifier:ValueError; 180, argument_list; 181, identifier:_segyio; 182, identifier:segyiofd; 183, call; 184, string; 185, subscript; 186, identifier:samples; 187, call; 188, identifier:tracecount; 189, identifier:tracecount; 190, identifier:format; 191, call; 192, identifier:ext_headers; 193, call; 194, identifier:segyio; 195, identifier:SegyFile; 196, identifier:fd; 197, keyword_argument; 198, keyword_argument; 199, keyword_argument; 200, keyword_argument; 201, keyword_argument; 202, identifier:sorting; 203, conditional_expression:spec.sorting if hasattr(spec, 'sorting') else None; 204, identifier:sorting; 205, None; 206, expression_statement; 207, attribute; 208, argument_list; 209, identifier:f; 210, identifier:text; 211, attribute; 212, attribute; 213, attribute; 214, identifier:samples; 215, identifier:interval; 216, call; 217, assignment; 218, identifier:f; 219, identifier:bin; 220, identifier:ntrpr; 221, identifier:tracecount; 222, identifier:nart; 223, identifier:tracecount; 224, identifier:hdt; 225, identifier:interval; 226, identifier:dto; 227, identifier:interval; 228, identifier:hns; 229, call; 230, identifier:nso; 231, call; 232, identifier:format; 233, call; 234, identifier:exth; 235, identifier:ext_headers; 236, identifier:spec; 237, identifier:tracecount; 238, identifier:tracecount; 239, binary_operator:len(spec.ilines) * len(spec.xlines) * len(spec.offsets); 240, identifier:spec; 241, string; 242, identifier:spec; 243, identifier:samples; 244, string_content:lsb; 245, string_content:little; 246, string_content:msb; 247, string_content:big; 248, identifier:spec; 249, string; 250, string_content:big; 251, string_content:unknown endianness {}, expected one of:; 252, attribute; 253, argument_list; 254, binary_operator:problem.format(endian) + opts; 255, identifier:str; 256, argument_list; 257, string_content:w+; 258, identifier:endians; 259, identifier:endian; 260, identifier:len; 261, argument_list; 262, identifier:int; 263, argument_list; 264, identifier:int; 265, argument_list; 266, identifier:filename; 267, call; 268, identifier:mode; 269, string; 270, identifier:iline; 271, call; 272, identifier:xline; 273, call; 274, identifier:endian; 275, identifier:endian; 276, attribute; 277, call; 278, None; 279, assignment; 280, identifier:f; 281, identifier:interpret; 282, attribute; 283, attribute; 284, attribute; 285, identifier:sorting; 286, identifier:f; 287, identifier:_il; 288, identifier:f; 289, identifier:_xl; 290, attribute; 291, identifier:offset; 292, identifier:int; 293, argument_list; 294, identifier:interval; 295, call; 296, identifier:len; 297, argument_list; 298, identifier:len; 299, argument_list; 300, identifier:int; 301, argument_list; 302, binary_operator:len(spec.ilines) * len(spec.xlines); 303, call; 304, string_content:ext_headers; 305, string_content:endian; 306, string; 307, identifier:join; 308, call; 309, call; 310, identifier:opts; 311, identifier:filename; 312, identifier:samples; 313, attribute; 314, identifier:ext_headers; 315, identifier:str; 316, argument_list; 317, string_content:w+; 318, identifier:int; 319, argument_list; 320, identifier:int; 321, argument_list; 322, identifier:spec; 323, identifier:sorting; 324, identifier:hasattr; 325, argument_list; 326, identifier:sorting; 327, attribute; 328, identifier:spec; 329, identifier:ilines; 330, identifier:spec; 331, identifier:xlines; 332, identifier:spec; 333, identifier:offsets; 334, identifier:segyio; 335, identifier:TraceField; 336, binary_operator:samples[0] * 1000; 337, identifier:int; 338, argument_list; 339, identifier:samples; 340, identifier:samples; 341, attribute; 342, call; 343, call; 344, identifier:len; 345, argument_list; 346, string_content:; 347, attribute; 348, argument_list; 349, attribute; 350, argument_list; 351, identifier:spec; 352, identifier:format; 353, identifier:filename; 354, attribute; 355, attribute; 356, identifier:spec; 357, string; 358, identifier:TraceSortingFormat; 359, identifier:INLINE_SORTING; 360, subscript; 361, integer:1000; 362, binary_operator:(samples[1] - samples[0]) * 1000; 363, identifier:spec; 364, identifier:format; 365, identifier:len; 366, argument_list; 367, identifier:len; 368, argument_list; 369, attribute; 370, identifier:endians; 371, identifier:keys; 372, identifier:problem; 373, identifier:format; 374, identifier:endian; 375, identifier:spec; 376, identifier:iline; 377, identifier:spec; 378, identifier:xline; 379, string_content:sorting; 380, identifier:samples; 381, integer:0; 382, parenthesized_expression; 383, integer:1000; 384, attribute; 385, attribute; 386, identifier:spec; 387, identifier:offsets; 388, binary_operator:samples[1] - samples[0]; 389, identifier:spec; 390, identifier:ilines; 391, identifier:spec; 392, identifier:xlines; 393, subscript; 394, subscript; 395, identifier:samples; 396, integer:1; 397, identifier:samples; 398, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 7, 25; 8, 26; 8, 27; 9, 28; 9, 29; 9, 30; 10, 31; 11, 32; 12, 33; 13, 34; 14, 35; 14, 36; 15, 37; 15, 38; 16, 39; 17, 40; 18, 41; 19, 42; 20, 43; 20, 44; 21, 45; 22, 46; 22, 47; 22, 48; 23, 49; 24, 50; 26, 51; 27, 52; 28, 53; 29, 54; 30, 55; 31, 56; 31, 57; 32, 58; 32, 59; 33, 60; 33, 61; 34, 62; 34, 63; 35, 64; 35, 65; 36, 66; 37, 67; 37, 68; 38, 69; 38, 70; 38, 71; 39, 72; 39, 73; 40, 74; 40, 75; 41, 76; 41, 77; 42, 78; 42, 79; 43, 80; 43, 81; 44, 82; 44, 83; 44, 84; 45, 85; 45, 86; 46, 87; 46, 88; 47, 89; 48, 90; 49, 91; 49, 92; 53, 93; 53, 94; 54, 95; 55, 96; 57, 97; 57, 98; 57, 99; 59, 100; 59, 101; 61, 102; 61, 103; 61, 104; 61, 105; 61, 106; 63, 107; 63, 108; 63, 109; 66, 110; 69, 111; 70, 112; 71, 113; 73, 114; 73, 115; 74, 116; 74, 117; 75, 118; 75, 119; 75, 120; 75, 121; 77, 122; 77, 123; 78, 124; 78, 125; 81, 126; 82, 127; 83, 128; 83, 129; 84, 130; 85, 131; 85, 132; 86, 133; 86, 134; 87, 135; 87, 136; 89, 137; 90, 138; 91, 139; 91, 140; 92, 141; 92, 142; 92, 143; 92, 144; 92, 145; 92, 146; 92, 147; 92, 148; 94, 149; 95, 150; 95, 151; 96, 152; 97, 153; 97, 154; 98, 155; 98, 156; 100, 157; 100, 158; 101, 159; 102, 160; 102, 161; 104, 162; 104, 163; 105, 164; 105, 165; 106, 166; 106, 167; 107, 168; 107, 169; 108, 170; 108, 171; 109, 172; 110, 173; 110, 174; 111, 175; 111, 176; 112, 177; 112, 178; 113, 179; 113, 180; 114, 181; 114, 182; 115, 183; 115, 184; 115, 185; 118, 186; 118, 187; 119, 188; 119, 189; 120, 190; 120, 191; 121, 192; 121, 193; 122, 194; 122, 195; 123, 196; 123, 197; 123, 198; 123, 199; 123, 200; 123, 201; 127, 202; 127, 203; 128, 204; 128, 205; 129, 206; 130, 207; 130, 208; 131, 209; 131, 210; 134, 211; 134, 212; 134, 213; 136, 214; 137, 215; 137, 216; 138, 217; 139, 218; 139, 219; 141, 220; 141, 221; 142, 222; 142, 223; 143, 224; 143, 225; 144, 226; 144, 227; 145, 228; 145, 229; 146, 230; 146, 231; 147, 232; 147, 233; 148, 234; 148, 235; 151, 236; 151, 237; 152, 238; 152, 239; 156, 240; 156, 241; 159, 242; 159, 243; 160, 244; 162, 245; 164, 246; 166, 247; 171, 248; 171, 249; 174, 250; 176, 251; 178, 252; 178, 253; 180, 254; 183, 255; 183, 256; 184, 257; 185, 258; 185, 259; 187, 260; 187, 261; 191, 262; 191, 263; 193, 264; 193, 265; 197, 266; 197, 267; 198, 268; 198, 269; 199, 270; 199, 271; 200, 272; 200, 273; 201, 274; 201, 275; 203, 276; 203, 277; 203, 278; 206, 279; 207, 280; 207, 281; 208, 282; 208, 283; 208, 284; 208, 285; 211, 286; 211, 287; 212, 288; 212, 289; 213, 290; 213, 291; 216, 292; 216, 293; 217, 294; 217, 295; 229, 296; 229, 297; 231, 298; 231, 299; 233, 300; 233, 301; 239, 302; 239, 303; 241, 304; 249, 305; 252, 306; 252, 307; 253, 308; 254, 309; 254, 310; 256, 311; 261, 312; 263, 313; 265, 314; 267, 315; 267, 316; 269, 317; 271, 318; 271, 319; 273, 320; 273, 321; 276, 322; 276, 323; 277, 324; 277, 325; 279, 326; 279, 327; 282, 328; 282, 329; 283, 330; 283, 331; 284, 332; 284, 333; 290, 334; 290, 335; 293, 336; 295, 337; 295, 338; 297, 339; 299, 340; 301, 341; 302, 342; 302, 343; 303, 344; 303, 345; 306, 346; 308, 347; 308, 348; 309, 349; 309, 350; 313, 351; 313, 352; 316, 353; 319, 354; 321, 355; 325, 356; 325, 357; 327, 358; 327, 359; 336, 360; 336, 361; 338, 362; 341, 363; 341, 364; 342, 365; 342, 366; 343, 367; 343, 368; 345, 369; 347, 370; 347, 371; 349, 372; 349, 373; 350, 374; 354, 375; 354, 376; 355, 377; 355, 378; 357, 379; 360, 380; 360, 381; 362, 382; 362, 383; 366, 384; 368, 385; 369, 386; 369, 387; 382, 388; 384, 389; 384, 390; 385, 391; 385, 392; 388, 393; 388, 394; 393, 395; 393, 396; 394, 397; 394, 398 | def create(filename, spec):
"""Create a new segy file.
Create a new segy file with the geometry and properties given by `spec`.
This enables creating SEGY files from your data. The created file supports
all segyio modes, but has an emphasis on writing. The spec must be
complete, otherwise an exception will be raised. A default, empty spec can
be created with ``segyio.spec()``.
Very little data is written to the file, so just calling create is not
sufficient to re-read the file with segyio. Rather, every trace header and
trace must be written to the file to be considered complete.
Create should be used together with python's ``with`` statement. This ensure
the data is written. Please refer to the examples.
The ``segyio.spec()`` function will default sorting, offsets and everything
in the mandatory group, except format and samples, and requires the caller
to fill in *all* the fields in either of the exclusive groups.
If any field is missing from the first exclusive group, and the tracecount
is set, the resulting file will be considered unstructured. If the
tracecount is set, and all fields of the first exclusive group are
specified, the file is considered structured and the tracecount is inferred
from the xlines/ilines/offsets. The offsets are defaulted to ``[1]`` by
``segyio.spec()``.
Parameters
----------
filename : str
Path to file to create
spec : segyio.spec
Structure of the segy file
Returns
-------
file : segyio.SegyFile
An open segyio file handle, similar to that returned by `segyio.open`
See also
--------
segyio.spec : template for the `spec` argument
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.4
Support for creating unstructured files
.. versionchanged:: 1.8
Support for creating lsb files
The ``spec`` is any object that has the following attributes
Mandatory::
iline : int or segyio.BinField
xline : int or segyio.BinField
samples : array of int
format : { 1, 5 }
1 = IBM float, 5 = IEEE float
Exclusive::
ilines : array_like of int
xlines : array_like of int
offsets : array_like of int
sorting : int or segyio.TraceSortingFormat
OR
tracecount : int
Optional::
ext_headers : int
endian : str { 'big', 'msb', 'little', 'lsb' }
defaults to 'big'
Examples
--------
Create a file:
>>> spec = segyio.spec()
>>> spec.ilines = [1, 2, 3, 4]
>>> spec.xlines = [11, 12, 13]
>>> spec.samples = list(range(50))
>>> spec.sorting = 2
>>> spec.format = 1
>>> with segyio.create(path, spec) as f:
... ## fill the file with data
... pass
...
Copy a file, but shorten all traces by 50 samples:
>>> with segyio.open(srcpath) as src:
... spec = segyio.spec()
... spec.sorting = src.sorting
... spec.format = src.format
... spec.samples = src.samples[:len(src.samples) - 50]
... spec.ilines = src.ilines
... spec.xline = src.xlines
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.trace = src.trace
Copy a file, but shift samples time by 50:
>>> with segyio.open(srcpath) as src:
... delrt = 50
... spec = segyio.spec()
... spec.samples = src.samples + delrt
... spec.ilines = src.ilines
... spec.xline = src.xlines
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.header = { TraceField.DelayRecordingTime: delrt }
... dst.trace = src.trace
Copy a file, but shorten all traces by 50 samples (since v1.4):
>>> with segyio.open(srcpath) as src:
... spec = segyio.tools.metadata(src)
... spec.samples = spec.samples[:len(spec.samples) - 50]
... with segyio.create(dstpath, spec) as dst:
... dst.text[0] = src.text[0]
... dst.bin = src.bin
... dst.header = src.header
... dst.trace = src.trace
"""
from . import _segyio
if not structured(spec):
tracecount = spec.tracecount
else:
tracecount = len(spec.ilines) * len(spec.xlines) * len(spec.offsets)
ext_headers = spec.ext_headers if hasattr(spec, 'ext_headers') else 0
samples = numpy.asarray(spec.samples)
endians = {
'lsb': 256, # (1 << 8)
'little': 256,
'msb': 0,
'big': 0,
}
endian = spec.endian if hasattr(spec, 'endian') else 'big'
if endian is None:
endian = 'big'
if endian not in endians:
problem = 'unknown endianness {}, expected one of: '
opts = ' '.join(endians.keys())
raise ValueError(problem.format(endian) + opts)
fd = _segyio.segyiofd(str(filename), 'w+', endians[endian])
fd.segymake(
samples = len(samples),
tracecount = tracecount,
format = int(spec.format),
ext_headers = int(ext_headers),
)
f = segyio.SegyFile(fd,
filename = str(filename),
mode = 'w+',
iline = int(spec.iline),
xline = int(spec.xline),
endian = endian,
)
f._samples = samples
if structured(spec):
sorting = spec.sorting if hasattr(spec, 'sorting') else None
if sorting is None:
sorting = TraceSortingFormat.INLINE_SORTING
f.interpret(spec.ilines, spec.xlines, spec.offsets, sorting)
f.text[0] = default_text_header(f._il, f._xl, segyio.TraceField.offset)
if len(samples) == 1:
interval = int(samples[0] * 1000)
else:
interval = int((samples[1] - samples[0]) * 1000)
f.bin.update(
ntrpr = tracecount,
nart = tracecount,
hdt = interval,
dto = interval,
hns = len(samples),
nso = len(samples),
format = int(spec.format),
exth = ext_headers,
)
return f |
0, module; 1, function_definition; 2, function_name:rotation; 3, parameters; 4, block; 5, identifier:f; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, return_statement; 16, identifier:line; 17, string; 18, comment:""" Find rotation of the survey
Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)``
The clock-wise rotation is defined as the angle in radians between line
given by the first and last trace of the first line and the axis that gives
increasing CDP-Y, in the direction that gives increasing CDP-X.
By default, the first line is the 'fast' direction, which is inlines if the
file is inline sorted, and crossline if it's crossline sorted.
Parameters
----------
f : SegyFile
line : { 'fast', 'slow', 'iline', 'xline' }
Returns
-------
rotation : float
cdpx : int
cdpy : int
Notes
-----
.. versionadded:: 1.2
"""; 19, attribute; 20, block; 21, assignment; 22, comparison_operator:line not in lines; 23, block; 24, assignment; 25, assignment; 26, assignment; 27, assignment; 28, expression_list; 29, string_content:fast; 30, identifier:f; 31, identifier:unstructured; 32, raise_statement; 33, identifier:lines; 34, dictionary; 35, identifier:line; 36, identifier:lines; 37, expression_statement; 38, expression_statement; 39, raise_statement; 40, identifier:l; 41, subscript; 42, identifier:origin; 43, subscript; 44, pattern_list; 45, expression_list; 46, identifier:rot; 47, call; 48, identifier:rot; 49, identifier:cdpx; 50, identifier:cdpy; 51, call; 52, pair; 53, pair; 54, pair; 55, pair; 56, assignment; 57, assignment; 58, call; 59, identifier:lines; 60, identifier:line; 61, subscript; 62, attribute; 63, attribute; 64, identifier:cdpx; 65, identifier:cdpy; 66, subscript; 67, subscript; 68, attribute; 69, argument_list; 70, identifier:ValueError; 71, argument_list; 72, string; 73, attribute; 74, string; 75, attribute; 76, string; 77, attribute; 78, string; 79, attribute; 80, identifier:error; 81, call; 82, identifier:solution; 83, call; 84, identifier:ValueError; 85, argument_list; 86, attribute; 87, integer:0; 88, attribute; 89, identifier:cdpx; 90, attribute; 91, identifier:cdpy; 92, identifier:origin; 93, attribute; 94, identifier:origin; 95, attribute; 96, attribute; 97, identifier:rotation; 98, call; 99, attribute; 100, call; 101, call; 102, string:"Rotation requires a structured file"; 103, string_content:fast; 104, identifier:f; 105, identifier:fast; 106, string_content:slow; 107, identifier:f; 108, identifier:slow; 109, string_content:iline; 110, identifier:f; 111, identifier:iline; 112, string_content:xline; 113, identifier:f; 114, identifier:xline; 115, attribute; 116, argument_list; 117, attribute; 118, argument_list; 119, call; 120, identifier:f; 121, identifier:header; 122, identifier:segyio; 123, identifier:su; 124, identifier:segyio; 125, identifier:su; 126, attribute; 127, identifier:cdpx; 128, attribute; 129, identifier:cdpy; 130, identifier:f; 131, identifier:xfd; 132, identifier:len; 133, argument_list; 134, identifier:l; 135, identifier:stride; 136, identifier:len; 137, argument_list; 138, attribute; 139, argument_list; 140, string:"Unknown line {}"; 141, identifier:format; 142, identifier:line; 143, string:"Must be any of: {}"; 144, identifier:format; 145, call; 146, attribute; 147, argument_list; 148, identifier:segyio; 149, identifier:su; 150, identifier:segyio; 151, identifier:su; 152, identifier:l; 153, attribute; 154, identifier:np; 155, identifier:fromiter; 156, call; 157, keyword_argument; 158, attribute; 159, argument_list; 160, string; 161, identifier:format; 162, identifier:error; 163, identifier:solution; 164, identifier:f; 165, identifier:offsets; 166, attribute; 167, argument_list; 168, identifier:dtype; 169, attribute; 170, string; 171, identifier:join; 172, call; 173, string_content:{} {}; 174, identifier:l; 175, identifier:keys; 176, identifier:np; 177, identifier:intc; 178, string_content:; 179, attribute; 180, argument_list; 181, identifier:lines; 182, identifier:keys | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 6, 16; 6, 17; 7, 18; 8, 19; 8, 20; 9, 21; 10, 22; 10, 23; 11, 24; 12, 25; 13, 26; 14, 27; 15, 28; 17, 29; 19, 30; 19, 31; 20, 32; 21, 33; 21, 34; 22, 35; 22, 36; 23, 37; 23, 38; 23, 39; 24, 40; 24, 41; 25, 42; 25, 43; 26, 44; 26, 45; 27, 46; 27, 47; 28, 48; 28, 49; 28, 50; 32, 51; 34, 52; 34, 53; 34, 54; 34, 55; 37, 56; 38, 57; 39, 58; 41, 59; 41, 60; 43, 61; 43, 62; 43, 63; 44, 64; 44, 65; 45, 66; 45, 67; 47, 68; 47, 69; 51, 70; 51, 71; 52, 72; 52, 73; 53, 74; 53, 75; 54, 76; 54, 77; 55, 78; 55, 79; 56, 80; 56, 81; 57, 82; 57, 83; 58, 84; 58, 85; 61, 86; 61, 87; 62, 88; 62, 89; 63, 90; 63, 91; 66, 92; 66, 93; 67, 94; 67, 95; 68, 96; 68, 97; 69, 98; 69, 99; 69, 100; 69, 101; 71, 102; 72, 103; 73, 104; 73, 105; 74, 106; 75, 107; 75, 108; 76, 109; 77, 110; 77, 111; 78, 112; 79, 113; 79, 114; 81, 115; 81, 116; 83, 117; 83, 118; 85, 119; 86, 120; 86, 121; 88, 122; 88, 123; 90, 124; 90, 125; 93, 126; 93, 127; 95, 128; 95, 129; 96, 130; 96, 131; 98, 132; 98, 133; 99, 134; 99, 135; 100, 136; 100, 137; 101, 138; 101, 139; 115, 140; 115, 141; 116, 142; 117, 143; 117, 144; 118, 145; 119, 146; 119, 147; 126, 148; 126, 149; 128, 150; 128, 151; 133, 152; 137, 153; 138, 154; 138, 155; 139, 156; 139, 157; 145, 158; 145, 159; 146, 160; 146, 161; 147, 162; 147, 163; 153, 164; 153, 165; 156, 166; 156, 167; 157, 168; 157, 169; 158, 170; 158, 171; 159, 172; 160, 173; 166, 174; 166, 175; 169, 176; 169, 177; 170, 178; 172, 179; 172, 180; 179, 181; 179, 182 | def rotation(f, line = 'fast'):
""" Find rotation of the survey
Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)``
The clock-wise rotation is defined as the angle in radians between line
given by the first and last trace of the first line and the axis that gives
increasing CDP-Y, in the direction that gives increasing CDP-X.
By default, the first line is the 'fast' direction, which is inlines if the
file is inline sorted, and crossline if it's crossline sorted.
Parameters
----------
f : SegyFile
line : { 'fast', 'slow', 'iline', 'xline' }
Returns
-------
rotation : float
cdpx : int
cdpy : int
Notes
-----
.. versionadded:: 1.2
"""
if f.unstructured:
raise ValueError("Rotation requires a structured file")
lines = { 'fast': f.fast,
'slow': f.slow,
'iline': f.iline,
'xline': f.xline,
}
if line not in lines:
error = "Unknown line {}".format(line)
solution = "Must be any of: {}".format(' '.join(lines.keys()))
raise ValueError('{} {}'.format(error, solution))
l = lines[line]
origin = f.header[0][segyio.su.cdpx, segyio.su.cdpy]
cdpx, cdpy = origin[segyio.su.cdpx], origin[segyio.su.cdpy]
rot = f.xfd.rotation( len(l),
l.stride,
len(f.offsets),
np.fromiter(l.keys(), dtype = np.intc) )
return rot, cdpx, cdpy |
0, module; 1, function_definition; 2, function_name:from_array3D; 3, parameters; 4, block; 5, identifier:filename; 6, identifier:data; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, if_statement; 16, expression_statement; 17, identifier:iline; 18, integer:189; 19, identifier:xline; 20, integer:193; 21, identifier:format; 22, attribute; 23, identifier:dt; 24, integer:4000; 25, identifier:delrt; 26, integer:0; 27, comment:""" Create a new SEGY file from a 3D array
Create an structured SEGY file with defaulted headers from a 3-dimensional
array. The file is inline-sorted. ilines, xlines and samples are inferred
from the array. Structure-defining fields in the binary header and
in the traceheaders are set accordingly. Such fields include, but are not
limited to iline, xline and offset. The file also contains a defaulted
textual header.
The 3-dimensional array is interpreted as::
xl0 xl1 xl2
-----------------
/ | tr0 | tr1 | tr2 | il0
-----------------
| / | tr3 | tr4 | tr5 | il1
-----------------
| / | tr6 | tr7 | tr8 | il2
-----------------
| / / / / n-samples
------------------
ilines = [1, len(axis(0) + 1]
xlines = [1, len(axis(1) + 1]
samples = [0, len(axis(2)]
Parameters
----------
filename : string-like
Path to new file
data : 3-dimensional array-like
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
format : int or segyio.SegySampleFormat
Sample format field in the trace header. Defaults to IBM float 4 byte
dt : int-like
sample interval
delrt : int-like
Notes
-----
.. versionadded:: 1.8
Examples
--------
Create a file from a 3D array, open it and read an iline:
>>> segyio.tools.from_array3D(path, array3d)
>>> segyio.open(path, mode) as f:
... iline = f.iline[0]
...
"""; 28, assignment; 29, assignment; 30, comparison_operator:dimensions != 3; 31, block; 32, call; 33, identifier:SegySampleFormat; 34, identifier:IBM_FLOAT_4_BYTE; 35, identifier:data; 36, call; 37, identifier:dimensions; 38, call; 39, identifier:dimensions; 40, integer:3; 41, expression_statement; 42, raise_statement; 43, identifier:from_array; 44, argument_list; 45, attribute; 46, argument_list; 47, identifier:len; 48, argument_list; 49, assignment; 50, call; 51, identifier:filename; 52, identifier:data; 53, keyword_argument; 54, keyword_argument; 55, keyword_argument; 56, keyword_argument; 57, keyword_argument; 58, identifier:np; 59, identifier:asarray; 60, identifier:data; 61, attribute; 62, identifier:problem; 63, call; 64, identifier:ValueError; 65, argument_list; 66, identifier:iline; 67, identifier:iline; 68, identifier:xline; 69, identifier:xline; 70, identifier:format; 71, identifier:format; 72, identifier:dt; 73, identifier:dt; 74, identifier:delrt; 75, identifier:delrt; 76, identifier:data; 77, identifier:shape; 78, attribute; 79, argument_list; 80, identifier:problem; 81, string:"Expected 3 dimensions, {} was given"; 82, identifier:format; 83, identifier:dimensions | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 7, 17; 7, 18; 8, 19; 8, 20; 9, 21; 9, 22; 10, 23; 10, 24; 11, 25; 11, 26; 12, 27; 13, 28; 14, 29; 15, 30; 15, 31; 16, 32; 22, 33; 22, 34; 28, 35; 28, 36; 29, 37; 29, 38; 30, 39; 30, 40; 31, 41; 31, 42; 32, 43; 32, 44; 36, 45; 36, 46; 38, 47; 38, 48; 41, 49; 42, 50; 44, 51; 44, 52; 44, 53; 44, 54; 44, 55; 44, 56; 44, 57; 45, 58; 45, 59; 46, 60; 48, 61; 49, 62; 49, 63; 50, 64; 50, 65; 53, 66; 53, 67; 54, 68; 54, 69; 55, 70; 55, 71; 56, 72; 56, 73; 57, 74; 57, 75; 61, 76; 61, 77; 63, 78; 63, 79; 65, 80; 78, 81; 78, 82; 79, 83 | def from_array3D(filename, data, iline=189,
xline=193,
format=SegySampleFormat.IBM_FLOAT_4_BYTE,
dt=4000,
delrt=0):
""" Create a new SEGY file from a 3D array
Create an structured SEGY file with defaulted headers from a 3-dimensional
array. The file is inline-sorted. ilines, xlines and samples are inferred
from the array. Structure-defining fields in the binary header and
in the traceheaders are set accordingly. Such fields include, but are not
limited to iline, xline and offset. The file also contains a defaulted
textual header.
The 3-dimensional array is interpreted as::
xl0 xl1 xl2
-----------------
/ | tr0 | tr1 | tr2 | il0
-----------------
| / | tr3 | tr4 | tr5 | il1
-----------------
| / | tr6 | tr7 | tr8 | il2
-----------------
| / / / / n-samples
------------------
ilines = [1, len(axis(0) + 1]
xlines = [1, len(axis(1) + 1]
samples = [0, len(axis(2)]
Parameters
----------
filename : string-like
Path to new file
data : 3-dimensional array-like
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
format : int or segyio.SegySampleFormat
Sample format field in the trace header. Defaults to IBM float 4 byte
dt : int-like
sample interval
delrt : int-like
Notes
-----
.. versionadded:: 1.8
Examples
--------
Create a file from a 3D array, open it and read an iline:
>>> segyio.tools.from_array3D(path, array3d)
>>> segyio.open(path, mode) as f:
... iline = f.iline[0]
...
"""
data = np.asarray(data)
dimensions = len(data.shape)
if dimensions != 3:
problem = "Expected 3 dimensions, {} was given".format(dimensions)
raise ValueError(problem)
from_array(filename, data, iline=iline, xline=xline, format=format,
dt=dt,
delrt=delrt) |
0, module; 1, function_definition; 2, function_name:open; 3, parameters; 4, block; 5, identifier:filename; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, expression_statement; 13, if_statement; 14, expression_statement; 15, if_statement; 16, import_from_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, try_statement; 22, if_statement; 23, return_statement; 24, identifier:mode; 25, string:"r"; 26, identifier:iline; 27, integer:189; 28, identifier:xline; 29, integer:193; 30, identifier:strict; 31, True; 32, identifier:ignore_geometry; 33, False; 34, identifier:endian; 35, string; 36, comment:"""Open a segy file.
Opens a segy file and tries to figure out its sorting, inline numbers,
crossline numbers, and offsets, and enables reading and writing to this
file in a simple manner.
For reading, the access mode `r` is preferred. All write operations will
raise an exception. For writing, the mode `r+` is preferred (as `rw` would
truncate the file). Any mode with `w` will raise an error. The modes used
are standard C file modes; please refer to that documentation for a
complete reference.
Open should be used together with python's ``with`` statement. Please refer
to the examples. When the ``with`` statement is used the file will
automatically be closed when the routine completes or an exception is
raised.
By default, segyio tries to open in ``strict`` mode. This means the file will
be assumed to represent a geometry with consistent inline, crosslines and
offsets. If strict is False, segyio will still try to establish a geometry,
but it won't abort if it fails. When in non-strict mode is opened,
geometry-dependent modes such as iline will raise an error.
If ``ignore_geometry=True``, segyio will *not* try to build iline/xline or
other geometry related structures, which leads to faster opens. This is
essentially the same as using ``strict=False`` on a file that has no
geometry.
Parameters
----------
filename : str
Path to file to open
mode : {'r', 'r+'}
File access mode, read-only ('r', default) or read-write ('r+')
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
strict : bool, optional
Abort if a geometry cannot be inferred. Defaults to True.
ignore_geometry : bool, optional
Opt out on building geometry information, useful for e.g. shot
organised files. Defaults to False.
endian : {'big', 'msb', 'little', 'lsb'}
File endianness, big/msb (default) or little/lsb
Returns
-------
file : segyio.SegyFile
An open segyio file handle
Raises
------
ValueError
If the mode string contains 'w', as it would truncate the file
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.8
endian argument
When a file is opened non-strict, only raw traces access is allowed, and
using modes such as ``iline`` raise an error.
Examples
--------
Open a file in read-only mode:
>>> with segyio.open(path, "r") as f:
... print(f.ilines)
...
[1, 2, 3, 4, 5]
Open a file in read-write mode:
>>> with segyio.open(path, "r+") as f:
... f.trace = np.arange(100)
Open two files at once:
>>> with segyio.open(path) as src, segyio.open(path, "r+") as dst:
... dst.trace = src.trace # copy all traces from src to dst
Open a file little-endian file:
>>> with segyio.open(path, endian = 'little') as f:
... f.trace[0]
"""; 37, comparison_operator:'w' in mode; 38, block; 39, assignment; 40, comparison_operator:endian not in endians; 41, block; 42, relative_import; 43, dotted_name; 44, assignment; 45, call; 46, assignment; 47, assignment; 48, block; 49, except_clause; 50, identifier:ignore_geometry; 51, block; 52, call; 53, string_content:big; 54, string; 55, identifier:mode; 56, expression_statement; 57, expression_statement; 58, raise_statement; 59, identifier:endians; 60, dictionary; 61, identifier:endian; 62, identifier:endians; 63, expression_statement; 64, expression_statement; 65, raise_statement; 66, import_prefix; 67, identifier:_segyio; 68, identifier:fd; 69, call; 70, attribute; 71, argument_list; 72, identifier:metrics; 73, call; 74, identifier:f; 75, call; 76, expression_statement; 77, expression_statement; 78, expression_statement; 79, expression_statement; 80, block; 81, return_statement; 82, identifier:infer_geometry; 83, argument_list; 84, string_content:w; 85, assignment; 86, assignment; 87, call; 88, pair; 89, comment:# (1 << 8); 90, pair; 91, pair; 92, pair; 93, assignment; 94, assignment; 95, call; 96, attribute; 97, argument_list; 98, identifier:fd; 99, identifier:segyopen; 100, attribute; 101, argument_list; 102, attribute; 103, argument_list; 104, assignment; 105, assignment; 106, assignment; 107, assignment; 108, expression_statement; 109, raise_statement; 110, identifier:f; 111, identifier:f; 112, identifier:metrics; 113, identifier:iline; 114, identifier:xline; 115, identifier:strict; 116, identifier:problem; 117, string; 118, identifier:solution; 119, string; 120, identifier:ValueError; 121, argument_list; 122, string; 123, integer:256; 124, string; 125, integer:256; 126, string; 127, integer:0; 128, string; 129, integer:0; 130, identifier:problem; 131, string; 132, identifier:opts; 133, call; 134, identifier:ValueError; 135, argument_list; 136, identifier:_segyio; 137, identifier:segyiofd; 138, call; 139, identifier:mode; 140, subscript; 141, identifier:fd; 142, identifier:metrics; 143, identifier:segyio; 144, identifier:SegyFile; 145, identifier:fd; 146, keyword_argument; 147, keyword_argument; 148, keyword_argument; 149, keyword_argument; 150, keyword_argument; 151, identifier:dt; 152, binary_operator:segyio.tools.dt(f, fallback_dt = 4000.0) / 1000.0; 153, identifier:t0; 154, subscript; 155, identifier:samples; 156, subscript; 157, attribute; 158, binary_operator:(numpy.arange(samples) * dt) + t0; 159, call; 160, string_content:w in mode would truncate the file; 161, string_content:use r+ to open in read-write; 162, call; 163, string_content:little; 164, string_content:lsb; 165, string_content:big; 166, string_content:msb; 167, string_content:unknown endianness {}, expected one of:; 168, attribute; 169, argument_list; 170, binary_operator:problem.format(endian) + opts; 171, identifier:str; 172, argument_list; 173, identifier:endians; 174, identifier:endian; 175, identifier:filename; 176, call; 177, identifier:mode; 178, identifier:mode; 179, identifier:iline; 180, identifier:iline; 181, identifier:xline; 182, identifier:xline; 183, identifier:endian; 184, identifier:endian; 185, call; 186, float:1000.0; 187, subscript; 188, attribute; 189, identifier:metrics; 190, string; 191, identifier:f; 192, identifier:_samples; 193, parenthesized_expression; 194, identifier:t0; 195, attribute; 196, argument_list; 197, attribute; 198, argument_list; 199, string; 200, identifier:join; 201, call; 202, call; 203, identifier:opts; 204, identifier:filename; 205, identifier:str; 206, argument_list; 207, attribute; 208, argument_list; 209, attribute; 210, integer:0; 211, attribute; 212, identifier:DelayRecordingTime; 213, string_content:samplecount; 214, binary_operator:numpy.arange(samples) * dt; 215, identifier:f; 216, identifier:close; 217, string; 218, identifier:join; 219, tuple; 220, string_content:; 221, attribute; 222, argument_list; 223, attribute; 224, argument_list; 225, identifier:filename; 226, attribute; 227, identifier:dt; 228, identifier:f; 229, keyword_argument; 230, identifier:f; 231, identifier:header; 232, identifier:segyio; 233, identifier:TraceField; 234, call; 235, identifier:dt; 236, string_content:,; 237, identifier:problem; 238, identifier:solution; 239, identifier:endians; 240, identifier:keys; 241, identifier:problem; 242, identifier:format; 243, identifier:endian; 244, identifier:segyio; 245, identifier:tools; 246, identifier:fallback_dt; 247, float:4000.0; 248, attribute; 249, argument_list; 250, identifier:numpy; 251, identifier:arange; 252, identifier:samples | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 6, 24; 6, 25; 7, 26; 7, 27; 8, 28; 8, 29; 9, 30; 9, 31; 10, 32; 10, 33; 11, 34; 11, 35; 12, 36; 13, 37; 13, 38; 14, 39; 15, 40; 15, 41; 16, 42; 16, 43; 17, 44; 18, 45; 19, 46; 20, 47; 21, 48; 21, 49; 22, 50; 22, 51; 23, 52; 35, 53; 37, 54; 37, 55; 38, 56; 38, 57; 38, 58; 39, 59; 39, 60; 40, 61; 40, 62; 41, 63; 41, 64; 41, 65; 42, 66; 43, 67; 44, 68; 44, 69; 45, 70; 45, 71; 46, 72; 46, 73; 47, 74; 47, 75; 48, 76; 48, 77; 48, 78; 48, 79; 49, 80; 51, 81; 52, 82; 52, 83; 54, 84; 56, 85; 57, 86; 58, 87; 60, 88; 60, 89; 60, 90; 60, 91; 60, 92; 63, 93; 64, 94; 65, 95; 69, 96; 69, 97; 70, 98; 70, 99; 73, 100; 73, 101; 75, 102; 75, 103; 76, 104; 77, 105; 78, 106; 79, 107; 80, 108; 80, 109; 81, 110; 83, 111; 83, 112; 83, 113; 83, 114; 83, 115; 85, 116; 85, 117; 86, 118; 86, 119; 87, 120; 87, 121; 88, 122; 88, 123; 90, 124; 90, 125; 91, 126; 91, 127; 92, 128; 92, 129; 93, 130; 93, 131; 94, 132; 94, 133; 95, 134; 95, 135; 96, 136; 96, 137; 97, 138; 97, 139; 97, 140; 100, 141; 100, 142; 102, 143; 102, 144; 103, 145; 103, 146; 103, 147; 103, 148; 103, 149; 103, 150; 104, 151; 104, 152; 105, 153; 105, 154; 106, 155; 106, 156; 107, 157; 107, 158; 108, 159; 117, 160; 119, 161; 121, 162; 122, 163; 124, 164; 126, 165; 128, 166; 131, 167; 133, 168; 133, 169; 135, 170; 138, 171; 138, 172; 140, 173; 140, 174; 146, 175; 146, 176; 147, 177; 147, 178; 148, 179; 148, 180; 149, 181; 149, 182; 150, 183; 150, 184; 152, 185; 152, 186; 154, 187; 154, 188; 156, 189; 156, 190; 157, 191; 157, 192; 158, 193; 158, 194; 159, 195; 159, 196; 162, 197; 162, 198; 168, 199; 168, 200; 169, 201; 170, 202; 170, 203; 172, 204; 176, 205; 176, 206; 185, 207; 185, 208; 187, 209; 187, 210; 188, 211; 188, 212; 190, 213; 193, 214; 195, 215; 195, 216; 197, 217; 197, 218; 198, 219; 199, 220; 201, 221; 201, 222; 202, 223; 202, 224; 206, 225; 207, 226; 207, 227; 208, 228; 208, 229; 209, 230; 209, 231; 211, 232; 211, 233; 214, 234; 214, 235; 217, 236; 219, 237; 219, 238; 221, 239; 221, 240; 223, 241; 223, 242; 224, 243; 226, 244; 226, 245; 229, 246; 229, 247; 234, 248; 234, 249; 248, 250; 248, 251; 249, 252 | def open(filename, mode="r", iline = 189,
xline = 193,
strict = True,
ignore_geometry = False,
endian = 'big'):
"""Open a segy file.
Opens a segy file and tries to figure out its sorting, inline numbers,
crossline numbers, and offsets, and enables reading and writing to this
file in a simple manner.
For reading, the access mode `r` is preferred. All write operations will
raise an exception. For writing, the mode `r+` is preferred (as `rw` would
truncate the file). Any mode with `w` will raise an error. The modes used
are standard C file modes; please refer to that documentation for a
complete reference.
Open should be used together with python's ``with`` statement. Please refer
to the examples. When the ``with`` statement is used the file will
automatically be closed when the routine completes or an exception is
raised.
By default, segyio tries to open in ``strict`` mode. This means the file will
be assumed to represent a geometry with consistent inline, crosslines and
offsets. If strict is False, segyio will still try to establish a geometry,
but it won't abort if it fails. When in non-strict mode is opened,
geometry-dependent modes such as iline will raise an error.
If ``ignore_geometry=True``, segyio will *not* try to build iline/xline or
other geometry related structures, which leads to faster opens. This is
essentially the same as using ``strict=False`` on a file that has no
geometry.
Parameters
----------
filename : str
Path to file to open
mode : {'r', 'r+'}
File access mode, read-only ('r', default) or read-write ('r+')
iline : int or segyio.TraceField
Inline number field in the trace headers. Defaults to 189 as per the
SEG-Y rev1 specification
xline : int or segyio.TraceField
Crossline number field in the trace headers. Defaults to 193 as per the
SEG-Y rev1 specification
strict : bool, optional
Abort if a geometry cannot be inferred. Defaults to True.
ignore_geometry : bool, optional
Opt out on building geometry information, useful for e.g. shot
organised files. Defaults to False.
endian : {'big', 'msb', 'little', 'lsb'}
File endianness, big/msb (default) or little/lsb
Returns
-------
file : segyio.SegyFile
An open segyio file handle
Raises
------
ValueError
If the mode string contains 'w', as it would truncate the file
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.8
endian argument
When a file is opened non-strict, only raw traces access is allowed, and
using modes such as ``iline`` raise an error.
Examples
--------
Open a file in read-only mode:
>>> with segyio.open(path, "r") as f:
... print(f.ilines)
...
[1, 2, 3, 4, 5]
Open a file in read-write mode:
>>> with segyio.open(path, "r+") as f:
... f.trace = np.arange(100)
Open two files at once:
>>> with segyio.open(path) as src, segyio.open(path, "r+") as dst:
... dst.trace = src.trace # copy all traces from src to dst
Open a file little-endian file:
>>> with segyio.open(path, endian = 'little') as f:
... f.trace[0]
"""
if 'w' in mode:
problem = 'w in mode would truncate the file'
solution = 'use r+ to open in read-write'
raise ValueError(', '.join((problem, solution)))
endians = {
'little': 256, # (1 << 8)
'lsb': 256,
'big': 0,
'msb': 0,
}
if endian not in endians:
problem = 'unknown endianness {}, expected one of: '
opts = ' '.join(endians.keys())
raise ValueError(problem.format(endian) + opts)
from . import _segyio
fd = _segyio.segyiofd(str(filename), mode, endians[endian])
fd.segyopen()
metrics = fd.metrics()
f = segyio.SegyFile(fd,
filename = str(filename),
mode = mode,
iline = iline,
xline = xline,
endian = endian,
)
try:
dt = segyio.tools.dt(f, fallback_dt = 4000.0) / 1000.0
t0 = f.header[0][segyio.TraceField.DelayRecordingTime]
samples = metrics['samplecount']
f._samples = (numpy.arange(samples) * dt) + t0
except:
f.close()
raise
if ignore_geometry:
return f
return infer_geometry(f, metrics, iline, xline, strict) |
0, module; 1, function_definition; 2, function_name:calc_min_interval; 3, parameters; 4, block; 5, identifier:x; 6, identifier:alpha; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, return_statement; 18, comment:"""Internal method to determine the minimum interval of
a given width
Assumes that x is sorted numpy array.
"""; 19, assignment; 20, assignment; 21, assignment; 22, assignment; 23, assignment; 24, comparison_operator:len(interval_width) == 0; 25, block; 26, assignment; 27, assignment; 28, assignment; 29, list; 30, identifier:n; 31, call; 32, identifier:cred_mass; 33, binary_operator:1.0 - alpha; 34, identifier:interval_idx_inc; 35, call; 36, identifier:n_intervals; 37, binary_operator:n - interval_idx_inc; 38, identifier:interval_width; 39, binary_operator:x[interval_idx_inc:] - x[:n_intervals]; 40, call; 41, integer:0; 42, expression_statement; 43, return_statement; 44, identifier:min_idx; 45, call; 46, identifier:hdi_min; 47, subscript; 48, identifier:hdi_max; 49, subscript; 50, identifier:hdi_min; 51, identifier:hdi_max; 52, identifier:len; 53, argument_list; 54, float:1.0; 55, identifier:alpha; 56, identifier:int; 57, argument_list; 58, identifier:n; 59, identifier:interval_idx_inc; 60, subscript; 61, subscript; 62, identifier:len; 63, argument_list; 64, call; 65, list; 66, attribute; 67, argument_list; 68, identifier:x; 69, identifier:min_idx; 70, identifier:x; 71, binary_operator:min_idx + interval_idx_inc; 72, identifier:x; 73, call; 74, identifier:x; 75, slice; 76, identifier:x; 77, slice; 78, identifier:interval_width; 79, identifier:print_; 80, argument_list; 81, None; 82, None; 83, identifier:np; 84, identifier:argmin; 85, identifier:interval_width; 86, identifier:min_idx; 87, identifier:interval_idx_inc; 88, attribute; 89, argument_list; 90, identifier:interval_idx_inc; 91, identifier:n_intervals; 92, string; 93, identifier:np; 94, identifier:floor; 95, binary_operator:cred_mass * n; 96, string_content:Too few elements for interval calculation; 97, identifier:cred_mass; 98, identifier:n | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 7, 18; 8, 19; 9, 20; 10, 21; 11, 22; 12, 23; 13, 24; 13, 25; 14, 26; 15, 27; 16, 28; 17, 29; 19, 30; 19, 31; 20, 32; 20, 33; 21, 34; 21, 35; 22, 36; 22, 37; 23, 38; 23, 39; 24, 40; 24, 41; 25, 42; 25, 43; 26, 44; 26, 45; 27, 46; 27, 47; 28, 48; 28, 49; 29, 50; 29, 51; 31, 52; 31, 53; 33, 54; 33, 55; 35, 56; 35, 57; 37, 58; 37, 59; 39, 60; 39, 61; 40, 62; 40, 63; 42, 64; 43, 65; 45, 66; 45, 67; 47, 68; 47, 69; 49, 70; 49, 71; 53, 72; 57, 73; 60, 74; 60, 75; 61, 76; 61, 77; 63, 78; 64, 79; 64, 80; 65, 81; 65, 82; 66, 83; 66, 84; 67, 85; 71, 86; 71, 87; 73, 88; 73, 89; 75, 90; 77, 91; 80, 92; 88, 93; 88, 94; 89, 95; 92, 96; 95, 97; 95, 98 | def calc_min_interval(x, alpha):
"""Internal method to determine the minimum interval of
a given width
Assumes that x is sorted numpy array.
"""
n = len(x)
cred_mass = 1.0 - alpha
interval_idx_inc = int(np.floor(cred_mass * n))
n_intervals = n - interval_idx_inc
interval_width = x[interval_idx_inc:] - x[:n_intervals]
if len(interval_width) == 0:
print_('Too few elements for interval calculation')
return [None, None]
min_idx = np.argmin(interval_width)
hdi_min = x[min_idx]
hdi_max = x[min_idx + interval_idx_inc]
return [hdi_min, hdi_max] |
0, module; 1, function_definition; 2, function_name:_compute_gas_price; 3, parameters; 4, block; 5, identifier:probabilities; 6, identifier:desired_probability; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, for_statement; 12, comment:"""
Given a sorted range of ``Probability`` named-tuples returns a gas price
computed based on where the ``desired_probability`` would fall within the
range.
:param probabilities: An iterable of `Probability` named-tuples sorted in reverse order.
:param desired_probability: An floating point representation of the desired
probability. (e.g. ``85% -> 0.85``)
"""; 13, assignment; 14, assignment; 15, comparison_operator:desired_probability >= first.prob; 16, block; 17, elif_clause; 18, pattern_list; 19, call; 20, block; 21, else_clause; 22, identifier:first; 23, subscript; 24, identifier:last; 25, subscript; 26, identifier:desired_probability; 27, attribute; 28, return_statement; 29, comparison_operator:desired_probability <= last.prob; 30, block; 31, identifier:left; 32, identifier:right; 33, identifier:sliding_window; 34, argument_list; 35, if_statement; 36, expression_statement; 37, expression_statement; 38, expression_statement; 39, expression_statement; 40, expression_statement; 41, return_statement; 42, comment:# The initial `if/else` clause in this function handles the case where; 43, comment:# the `desired_probability` is either above or below the min/max; 44, comment:# probability found in the `probabilities`.; 45, comment:#; 46, comment:# With these two cases handled, the only way this code block should be; 47, comment:# reachable would be if the `probabilities` were not sorted correctly.; 48, comment:# Otherwise, the `desired_probability` **must** fall between two of the; 49, comment:# values in the `probabilities``.; 50, block; 51, identifier:probabilities; 52, integer:0; 53, identifier:probabilities; 54, unary_operator; 55, identifier:first; 56, identifier:prob; 57, call; 58, identifier:desired_probability; 59, attribute; 60, return_statement; 61, integer:2; 62, identifier:probabilities; 63, comparison_operator:desired_probability < right.prob; 64, block; 65, elif_clause; 66, assignment; 67, assignment; 68, assignment; 69, assignment; 70, assignment; 71, identifier:gas_price; 72, raise_statement; 73, integer:1; 74, identifier:int; 75, argument_list; 76, identifier:last; 77, identifier:prob; 78, call; 79, identifier:desired_probability; 80, attribute; 81, continue_statement; 82, comparison_operator:desired_probability > left.prob; 83, comment:# This code block should never be reachable as it would indicate; 84, comment:# that we already passed by the probability window in which our; 85, comment:# `desired_probability` is located.; 86, block; 87, identifier:adj_prob; 88, binary_operator:desired_probability - right.prob; 89, identifier:window_size; 90, binary_operator:left.prob - right.prob; 91, identifier:position; 92, binary_operator:adj_prob / window_size; 93, identifier:gas_window_size; 94, binary_operator:left.gas_price - right.gas_price; 95, identifier:gas_price; 96, call; 97, call; 98, attribute; 99, identifier:int; 100, argument_list; 101, identifier:right; 102, identifier:prob; 103, identifier:desired_probability; 104, attribute; 105, raise_statement; 106, identifier:desired_probability; 107, attribute; 108, attribute; 109, attribute; 110, identifier:adj_prob; 111, identifier:window_size; 112, attribute; 113, attribute; 114, identifier:int; 115, argument_list; 116, identifier:Exception; 117, argument_list; 118, identifier:first; 119, identifier:gas_price; 120, attribute; 121, identifier:left; 122, identifier:prob; 123, call; 124, identifier:right; 125, identifier:prob; 126, identifier:left; 127, identifier:prob; 128, identifier:right; 129, identifier:prob; 130, identifier:left; 131, identifier:gas_price; 132, identifier:right; 133, identifier:gas_price; 134, call; 135, string; 136, identifier:last; 137, identifier:gas_price; 138, identifier:Exception; 139, argument_list; 140, attribute; 141, argument_list; 142, string_content:Invariant; 143, string; 144, identifier:math; 145, identifier:ceil; 146, binary_operator:right.gas_price + gas_window_size * position; 147, string_content:Invariant; 148, attribute; 149, binary_operator:gas_window_size * position; 150, identifier:right; 151, identifier:gas_price; 152, identifier:gas_window_size; 153, identifier:position | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 7, 12; 8, 13; 9, 14; 10, 15; 10, 16; 10, 17; 11, 18; 11, 19; 11, 20; 11, 21; 13, 22; 13, 23; 14, 24; 14, 25; 15, 26; 15, 27; 16, 28; 17, 29; 17, 30; 18, 31; 18, 32; 19, 33; 19, 34; 20, 35; 20, 36; 20, 37; 20, 38; 20, 39; 20, 40; 20, 41; 21, 42; 21, 43; 21, 44; 21, 45; 21, 46; 21, 47; 21, 48; 21, 49; 21, 50; 23, 51; 23, 52; 25, 53; 25, 54; 27, 55; 27, 56; 28, 57; 29, 58; 29, 59; 30, 60; 34, 61; 34, 62; 35, 63; 35, 64; 35, 65; 36, 66; 37, 67; 38, 68; 39, 69; 40, 70; 41, 71; 50, 72; 54, 73; 57, 74; 57, 75; 59, 76; 59, 77; 60, 78; 63, 79; 63, 80; 64, 81; 65, 82; 65, 83; 65, 84; 65, 85; 65, 86; 66, 87; 66, 88; 67, 89; 67, 90; 68, 91; 68, 92; 69, 93; 69, 94; 70, 95; 70, 96; 72, 97; 75, 98; 78, 99; 78, 100; 80, 101; 80, 102; 82, 103; 82, 104; 86, 105; 88, 106; 88, 107; 90, 108; 90, 109; 92, 110; 92, 111; 94, 112; 94, 113; 96, 114; 96, 115; 97, 116; 97, 117; 98, 118; 98, 119; 100, 120; 104, 121; 104, 122; 105, 123; 107, 124; 107, 125; 108, 126; 108, 127; 109, 128; 109, 129; 112, 130; 112, 131; 113, 132; 113, 133; 115, 134; 117, 135; 120, 136; 120, 137; 123, 138; 123, 139; 134, 140; 134, 141; 135, 142; 139, 143; 140, 144; 140, 145; 141, 146; 143, 147; 146, 148; 146, 149; 148, 150; 148, 151; 149, 152; 149, 153 | def _compute_gas_price(probabilities, desired_probability):
"""
Given a sorted range of ``Probability`` named-tuples returns a gas price
computed based on where the ``desired_probability`` would fall within the
range.
:param probabilities: An iterable of `Probability` named-tuples sorted in reverse order.
:param desired_probability: An floating point representation of the desired
probability. (e.g. ``85% -> 0.85``)
"""
first = probabilities[0]
last = probabilities[-1]
if desired_probability >= first.prob:
return int(first.gas_price)
elif desired_probability <= last.prob:
return int(last.gas_price)
for left, right in sliding_window(2, probabilities):
if desired_probability < right.prob:
continue
elif desired_probability > left.prob:
# This code block should never be reachable as it would indicate
# that we already passed by the probability window in which our
# `desired_probability` is located.
raise Exception('Invariant')
adj_prob = desired_probability - right.prob
window_size = left.prob - right.prob
position = adj_prob / window_size
gas_window_size = left.gas_price - right.gas_price
gas_price = int(math.ceil(right.gas_price + gas_window_size * position))
return gas_price
else:
# The initial `if/else` clause in this function handles the case where
# the `desired_probability` is either above or below the min/max
# probability found in the `probabilities`.
#
# With these two cases handled, the only way this code block should be
# reachable would be if the `probabilities` were not sorted correctly.
# Otherwise, the `desired_probability` **must** fall between two of the
# values in the `probabilities``.
raise Exception('Invariant') |
0, module; 1, function_definition; 2, function_name:generate_X_grid; 3, parameters; 4, block; 5, identifier:self; 6, identifier:term; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, if_statement; 11, comment:# cant do Intercept; 12, if_statement; 13, comment:# process each subterm in a TensorTerm; 14, if_statement; 15, identifier:n; 16, integer:100; 17, identifier:meshgrid; 18, False; 19, comment:"""create a nice grid of X data
array is sorted by feature and uniformly spaced,
so the marginal and joint distributions are likely wrong
if term is >= 0, we generate n samples per feature,
which results in n^deg samples,
where deg is the degree of the interaction of the term
Parameters
----------
term : int,
Which term to process.
n : int, optional
number of data points to create
meshgrid : bool, optional
Whether to return a meshgrid (useful for 3d plotting)
or a feature matrix (useful for inference like partial predictions)
Returns
-------
if meshgrid is False:
np.array of shape (n, n_features)
where m is the number of
(sub)terms in the requested (tensor)term.
else:
tuple of len m,
where m is the number of (sub)terms in the requested
(tensor)term.
each element in the tuple contains a np.ndarray of size (n)^m
Raises
------
ValueError :
If the term requested is an intercept
since it does not make sense to process the intercept term.
"""; 20, not_operator; 21, block; 22, attribute; 23, block; 24, attribute; 25, block; 26, comment:# all other Terms; 27, elif_clause; 28, comment:# dont know what to do here; 29, else_clause; 30, attribute; 31, raise_statement; 32, subscript; 33, identifier:isintercept; 34, raise_statement; 35, subscript; 36, identifier:istensor; 37, expression_statement; 38, for_statement; 39, expression_statement; 40, if_statement; 41, call; 42, block; 43, block; 44, identifier:self; 45, identifier:_is_fitted; 46, call; 47, attribute; 48, identifier:term; 49, call; 50, attribute; 51, identifier:term; 52, assignment; 53, identifier:term_; 54, subscript; 55, block; 56, assignment; 57, identifier:meshgrid; 58, block; 59, else_clause; 60, identifier:hasattr; 61, argument_list; 62, expression_statement; 63, if_statement; 64, comment:# fill in feature matrix with only relevant features for this term; 65, expression_statement; 66, expression_statement; 67, if_statement; 68, return_statement; 69, raise_statement; 70, identifier:AttributeError; 71, argument_list; 72, identifier:self; 73, identifier:terms; 74, identifier:ValueError; 75, argument_list; 76, identifier:self; 77, identifier:terms; 78, identifier:Xs; 79, list; 80, attribute; 81, identifier:term; 82, expression_statement; 83, identifier:Xs; 84, call; 85, return_statement; 86, block; 87, subscript; 88, string; 89, assignment; 90, identifier:meshgrid; 91, block; 92, assignment; 93, assignment; 94, comparison_operator:getattr(self.terms[term], 'by', None) is not None; 95, block; 96, identifier:X; 97, call; 98, string; 99, string; 100, identifier:self; 101, identifier:terms; 102, call; 103, attribute; 104, argument_list; 105, call; 106, return_statement; 107, attribute; 108, identifier:term; 109, string_content:edge_knots_; 110, identifier:x; 111, call; 112, return_statement; 113, identifier:X; 114, call; 115, subscript; 116, identifier:x; 117, call; 118, None; 119, expression_statement; 120, identifier:TypeError; 121, argument_list; 122, string_content:GAM has not been fitted. Call fit first.; 123, string_content:cannot create grid for intercept term; 124, attribute; 125, argument_list; 126, identifier:np; 127, identifier:meshgrid; 128, list_splat; 129, keyword_argument; 130, identifier:tuple; 131, argument_list; 132, call; 133, identifier:self; 134, identifier:terms; 135, attribute; 136, argument_list; 137, tuple; 138, attribute; 139, argument_list; 140, identifier:X; 141, slice; 142, attribute; 143, identifier:getattr; 144, argument_list; 145, assignment; 146, call; 147, identifier:Xs; 148, identifier:append; 149, call; 150, identifier:Xs; 151, identifier:indexing; 152, string; 153, identifier:Xs; 154, attribute; 155, argument_list; 156, identifier:np; 157, identifier:linspace; 158, subscript; 159, subscript; 160, keyword_argument; 161, identifier:x; 162, identifier:np; 163, identifier:zeros; 164, tuple; 165, subscript; 166, identifier:feature; 167, subscript; 168, string; 169, None; 170, subscript; 171, float:1.; 172, attribute; 173, argument_list; 174, attribute; 175, argument_list; 176, string_content:ij; 177, identifier:self; 178, identifier:_flatten_mesh; 179, identifier:Xs; 180, keyword_argument; 181, attribute; 182, integer:0; 183, attribute; 184, integer:1; 185, identifier:num; 186, identifier:n; 187, identifier:n; 188, subscript; 189, attribute; 190, identifier:term; 191, attribute; 192, identifier:term; 193, string_content:by; 194, identifier:X; 195, slice; 196, attribute; 197, string; 198, identifier:format; 199, subscript; 200, identifier:np; 201, identifier:linspace; 202, subscript; 203, subscript; 204, keyword_argument; 205, identifier:term; 206, identifier:term; 207, subscript; 208, identifier:edge_knots_; 209, subscript; 210, identifier:edge_knots_; 211, attribute; 212, string; 213, identifier:self; 214, identifier:terms; 215, identifier:self; 216, identifier:terms; 217, subscript; 218, identifier:by; 219, string_content:Unexpected term type: {}; 220, attribute; 221, identifier:term; 222, attribute; 223, integer:0; 224, attribute; 225, integer:1; 226, identifier:num; 227, identifier:n; 228, attribute; 229, identifier:term; 230, attribute; 231, identifier:term; 232, identifier:self; 233, identifier:statistics_; 234, string_content:m_features; 235, attribute; 236, identifier:term; 237, identifier:self; 238, identifier:terms; 239, identifier:term_; 240, identifier:edge_knots_; 241, identifier:term_; 242, identifier:edge_knots_; 243, identifier:self; 244, identifier:terms; 245, identifier:self; 246, identifier:terms; 247, identifier:self; 248, identifier:terms | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 7, 15; 7, 16; 8, 17; 8, 18; 9, 19; 10, 20; 10, 21; 12, 22; 12, 23; 14, 24; 14, 25; 14, 26; 14, 27; 14, 28; 14, 29; 20, 30; 21, 31; 22, 32; 22, 33; 23, 34; 24, 35; 24, 36; 25, 37; 25, 38; 25, 39; 25, 40; 27, 41; 27, 42; 29, 43; 30, 44; 30, 45; 31, 46; 32, 47; 32, 48; 34, 49; 35, 50; 35, 51; 37, 52; 38, 53; 38, 54; 38, 55; 39, 56; 40, 57; 40, 58; 40, 59; 41, 60; 41, 61; 42, 62; 42, 63; 42, 64; 42, 65; 42, 66; 42, 67; 42, 68; 43, 69; 46, 70; 46, 71; 47, 72; 47, 73; 49, 74; 49, 75; 50, 76; 50, 77; 52, 78; 52, 79; 54, 80; 54, 81; 55, 82; 56, 83; 56, 84; 58, 85; 59, 86; 61, 87; 61, 88; 62, 89; 63, 90; 63, 91; 65, 92; 66, 93; 67, 94; 67, 95; 68, 96; 69, 97; 71, 98; 75, 99; 80, 100; 80, 101; 82, 102; 84, 103; 84, 104; 85, 105; 86, 106; 87, 107; 87, 108; 88, 109; 89, 110; 89, 111; 91, 112; 92, 113; 92, 114; 93, 115; 93, 116; 94, 117; 94, 118; 95, 119; 97, 120; 97, 121; 98, 122; 99, 123; 102, 124; 102, 125; 103, 126; 103, 127; 104, 128; 104, 129; 105, 130; 105, 131; 106, 132; 107, 133; 107, 134; 111, 135; 111, 136; 112, 137; 114, 138; 114, 139; 115, 140; 115, 141; 115, 142; 117, 143; 117, 144; 119, 145; 121, 146; 124, 147; 124, 148; 125, 149; 128, 150; 129, 151; 129, 152; 131, 153; 132, 154; 132, 155; 135, 156; 135, 157; 136, 158; 136, 159; 136, 160; 137, 161; 138, 162; 138, 163; 139, 164; 142, 165; 142, 166; 144, 167; 144, 168; 144, 169; 145, 170; 145, 171; 146, 172; 146, 173; 149, 174; 149, 175; 152, 176; 154, 177; 154, 178; 155, 179; 155, 180; 158, 181; 158, 182; 159, 183; 159, 184; 160, 185; 160, 186; 164, 187; 164, 188; 165, 189; 165, 190; 167, 191; 167, 192; 168, 193; 170, 194; 170, 195; 170, 196; 172, 197; 172, 198; 173, 199; 174, 200; 174, 201; 175, 202; 175, 203; 175, 204; 180, 205; 180, 206; 181, 207; 181, 208; 183, 209; 183, 210; 188, 211; 188, 212; 189, 213; 189, 214; 191, 215; 191, 216; 196, 217; 196, 218; 197, 219; 199, 220; 199, 221; 202, 222; 202, 223; 203, 224; 203, 225; 204, 226; 204, 227; 207, 228; 207, 229; 209, 230; 209, 231; 211, 232; 211, 233; 212, 234; 217, 235; 217, 236; 220, 237; 220, 238; 222, 239; 222, 240; 224, 241; 224, 242; 228, 243; 228, 244; 230, 245; 230, 246; 235, 247; 235, 248 | def generate_X_grid(self, term, n=100, meshgrid=False):
"""create a nice grid of X data
array is sorted by feature and uniformly spaced,
so the marginal and joint distributions are likely wrong
if term is >= 0, we generate n samples per feature,
which results in n^deg samples,
where deg is the degree of the interaction of the term
Parameters
----------
term : int,
Which term to process.
n : int, optional
number of data points to create
meshgrid : bool, optional
Whether to return a meshgrid (useful for 3d plotting)
or a feature matrix (useful for inference like partial predictions)
Returns
-------
if meshgrid is False:
np.array of shape (n, n_features)
where m is the number of
(sub)terms in the requested (tensor)term.
else:
tuple of len m,
where m is the number of (sub)terms in the requested
(tensor)term.
each element in the tuple contains a np.ndarray of size (n)^m
Raises
------
ValueError :
If the term requested is an intercept
since it does not make sense to process the intercept term.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
# cant do Intercept
if self.terms[term].isintercept:
raise ValueError('cannot create grid for intercept term')
# process each subterm in a TensorTerm
if self.terms[term].istensor:
Xs = []
for term_ in self.terms[term]:
Xs.append(np.linspace(term_.edge_knots_[0],
term_.edge_knots_[1],
num=n))
Xs = np.meshgrid(*Xs, indexing='ij')
if meshgrid:
return tuple(Xs)
else:
return self._flatten_mesh(Xs, term=term)
# all other Terms
elif hasattr(self.terms[term], 'edge_knots_'):
x = np.linspace(self.terms[term].edge_knots_[0],
self.terms[term].edge_knots_[1],
num=n)
if meshgrid:
return (x,)
# fill in feature matrix with only relevant features for this term
X = np.zeros((n, self.statistics_['m_features']))
X[:, self.terms[term].feature] = x
if getattr(self.terms[term], 'by', None) is not None:
X[:, self.terms[term].by] = 1.
return X
# dont know what to do here
else:
raise TypeError('Unexpected term type: {}'.format(self.terms[term])) |
0, module; 1, function_definition; 2, function_name:build_from_info; 3, parameters; 4, block; 5, identifier:cls; 6, identifier:info; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""build a TensorTerm instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TensorTerm instance
"""; 12, assignment; 13, identifier:term_info; 14, subscript; 15, block; 16, call; 17, identifier:terms; 18, list; 19, identifier:info; 20, string; 21, expression_statement; 22, identifier:cls; 23, argument_list; 24, string_content:terms; 25, call; 26, list_splat; 27, attribute; 28, argument_list; 29, identifier:terms; 30, identifier:terms; 31, identifier:append; 32, call; 33, attribute; 34, argument_list; 35, identifier:SplineTerm; 36, identifier:build_from_info; 37, identifier:term_info | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 14, 19; 14, 20; 15, 21; 16, 22; 16, 23; 20, 24; 21, 25; 23, 26; 25, 27; 25, 28; 26, 29; 27, 30; 27, 31; 28, 32; 32, 33; 32, 34; 33, 35; 33, 36; 34, 37 | def build_from_info(cls, info):
"""build a TensorTerm instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TensorTerm instance
"""
terms = []
for term_info in info['terms']:
terms.append(SplineTerm.build_from_info(term_info))
return cls(*terms) |
0, module; 1, function_definition; 2, function_name:sort_kate_imports; 3, parameters; 4, block; 5, default_parameter; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, if_statement; 16, expression_statement; 17, identifier:add_imports; 18, tuple; 19, identifier:remove_imports; 20, tuple; 21, comment:"""Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes."""; 22, assignment; 23, assignment; 24, assignment; 25, assignment; 26, assignment; 27, call; 28, call; 29, identifier:selection; 30, block; 31, call; 32, identifier:document; 33, call; 34, identifier:view; 35, call; 36, identifier:position; 37, call; 38, identifier:selection; 39, call; 40, identifier:sorter; 41, call; 42, attribute; 43, argument_list; 44, attribute; 45, argument_list; 46, expression_statement; 47, expression_statement; 48, expression_statement; 49, expression_statement; 50, expression_statement; 51, expression_statement; 52, attribute; 53, argument_list; 54, attribute; 55, argument_list; 56, attribute; 57, argument_list; 58, attribute; 59, argument_list; 60, attribute; 61, argument_list; 62, identifier:SortImports; 63, argument_list; 64, identifier:document; 65, identifier:setText; 66, attribute; 67, identifier:position; 68, identifier:setLine; 69, binary_operator:position.line() + sorter.length_change; 70, assignment; 71, call; 72, assignment; 73, call; 74, call; 75, call; 76, identifier:view; 77, identifier:setCursorPosition; 78, identifier:position; 79, identifier:kate; 80, identifier:activeDocument; 81, identifier:document; 82, identifier:activeView; 83, identifier:view; 84, identifier:cursorPosition; 85, identifier:view; 86, identifier:selectionRange; 87, keyword_argument; 88, keyword_argument; 89, keyword_argument; 90, keyword_argument; 91, identifier:sorter; 92, identifier:output; 93, call; 94, attribute; 95, identifier:start; 96, call; 97, attribute; 98, argument_list; 99, identifier:end; 100, call; 101, attribute; 102, argument_list; 103, attribute; 104, argument_list; 105, attribute; 106, argument_list; 107, identifier:file_contents; 108, call; 109, identifier:add_imports; 110, identifier:add_imports; 111, identifier:remove_imports; 112, identifier:remove_imports; 113, identifier:settings_path; 114, call; 115, attribute; 116, argument_list; 117, identifier:sorter; 118, identifier:length_change; 119, attribute; 120, argument_list; 121, identifier:start; 122, identifier:setLine; 123, binary_operator:start.line() + sorter.length_change; 124, attribute; 125, argument_list; 126, identifier:end; 127, identifier:setLine; 128, binary_operator:end.line() + sorter.length_change; 129, identifier:selection; 130, identifier:setRange; 131, identifier:start; 132, identifier:end; 133, identifier:view; 134, identifier:setSelection; 135, identifier:selection; 136, attribute; 137, argument_list; 138, attribute; 139, argument_list; 140, identifier:position; 141, identifier:line; 142, identifier:selection; 143, identifier:start; 144, call; 145, attribute; 146, identifier:selection; 147, identifier:end; 148, call; 149, attribute; 150, identifier:document; 151, identifier:text; 152, attribute; 153, identifier:dirname; 154, call; 155, attribute; 156, argument_list; 157, identifier:sorter; 158, identifier:length_change; 159, attribute; 160, argument_list; 161, identifier:sorter; 162, identifier:length_change; 163, identifier:os; 164, identifier:path; 165, attribute; 166, argument_list; 167, identifier:start; 168, identifier:line; 169, identifier:end; 170, identifier:line; 171, attribute; 172, identifier:abspath; 173, call; 174, identifier:os; 175, identifier:path; 176, identifier:str; 177, argument_list; 178, call; 179, attribute; 180, argument_list; 181, call; 182, identifier:path; 183, attribute; 184, argument_list; 185, identifier:document; 186, identifier:url | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 5, 17; 5, 18; 6, 19; 6, 20; 7, 21; 8, 22; 9, 23; 10, 24; 11, 25; 12, 26; 13, 27; 14, 28; 15, 29; 15, 30; 16, 31; 22, 32; 22, 33; 23, 34; 23, 35; 24, 36; 24, 37; 25, 38; 25, 39; 26, 40; 26, 41; 27, 42; 27, 43; 28, 44; 28, 45; 30, 46; 30, 47; 30, 48; 30, 49; 30, 50; 30, 51; 31, 52; 31, 53; 33, 54; 33, 55; 35, 56; 35, 57; 37, 58; 37, 59; 39, 60; 39, 61; 41, 62; 41, 63; 42, 64; 42, 65; 43, 66; 44, 67; 44, 68; 45, 69; 46, 70; 47, 71; 48, 72; 49, 73; 50, 74; 51, 75; 52, 76; 52, 77; 53, 78; 54, 79; 54, 80; 56, 81; 56, 82; 58, 83; 58, 84; 60, 85; 60, 86; 63, 87; 63, 88; 63, 89; 63, 90; 66, 91; 66, 92; 69, 93; 69, 94; 70, 95; 70, 96; 71, 97; 71, 98; 72, 99; 72, 100; 73, 101; 73, 102; 74, 103; 74, 104; 75, 105; 75, 106; 87, 107; 87, 108; 88, 109; 88, 110; 89, 111; 89, 112; 90, 113; 90, 114; 93, 115; 93, 116; 94, 117; 94, 118; 96, 119; 96, 120; 97, 121; 97, 122; 98, 123; 100, 124; 100, 125; 101, 126; 101, 127; 102, 128; 103, 129; 103, 130; 104, 131; 104, 132; 105, 133; 105, 134; 106, 135; 108, 136; 108, 137; 114, 138; 114, 139; 115, 140; 115, 141; 119, 142; 119, 143; 123, 144; 123, 145; 124, 146; 124, 147; 128, 148; 128, 149; 136, 150; 136, 151; 138, 152; 138, 153; 139, 154; 144, 155; 144, 156; 145, 157; 145, 158; 148, 159; 148, 160; 149, 161; 149, 162; 152, 163; 152, 164; 154, 165; 154, 166; 155, 167; 155, 168; 159, 169; 159, 170; 165, 171; 165, 172; 166, 173; 171, 174; 171, 175; 173, 176; 173, 177; 177, 178; 178, 179; 178, 180; 179, 181; 179, 182; 181, 183; 181, 184; 183, 185; 183, 186 | def sort_kate_imports(add_imports=(), remove_imports=()):
"""Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes."""
document = kate.activeDocument()
view = document.activeView()
position = view.cursorPosition()
selection = view.selectionRange()
sorter = SortImports(file_contents=document.text(), add_imports=add_imports, remove_imports=remove_imports,
settings_path=os.path.dirname(os.path.abspath(str(document.url().path()))))
document.setText(sorter.output)
position.setLine(position.line() + sorter.length_change)
if selection:
start = selection.start()
start.setLine(start.line() + sorter.length_change)
end = selection.end()
end.setLine(end.line() + sorter.length_change)
selection.setRange(start, end)
view.setSelection(selection)
view.setCursorPosition(position) |
0, module; 1, function_definition; 2, function_name:_get_line; 3, parameters; 4, type; 5, block; 6, identifier:self; 7, identifier:str; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, comment:"""Returns the current line from the file while incrementing the index."""; 13, assignment; 14, augmented_assignment; 15, identifier:line; 16, identifier:line; 17, subscript; 18, attribute; 19, integer:1; 20, attribute; 21, attribute; 22, identifier:self; 23, identifier:index; 24, identifier:self; 25, identifier:in_lines; 26, identifier:self; 27, identifier:index | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 4, 7; 5, 8; 5, 9; 5, 10; 5, 11; 8, 12; 9, 13; 10, 14; 11, 15; 13, 16; 13, 17; 14, 18; 14, 19; 17, 20; 17, 21; 18, 22; 18, 23; 20, 24; 20, 25; 21, 26; 21, 27 | def _get_line(self) -> str:
"""Returns the current line from the file while incrementing the index."""
line = self.in_lines[self.index]
self.index += 1
return line |
0, module; 1, function_definition; 2, function_name:_add_comments; 3, parameters; 4, type; 5, block; 6, identifier:self; 7, typed_parameter; 8, typed_default_parameter; 9, identifier:str; 10, expression_statement; 11, if_statement; 12, if_statement; 13, identifier:comments; 14, type; 15, identifier:original_string; 16, type; 17, string:""; 18, comment:"""
Returns a string with comments added if ignore_comments is not set.
"""; 19, subscript; 20, block; 21, not_operator; 22, block; 23, else_clause; 24, generic_type; 25, identifier:str; 26, attribute; 27, string; 28, return_statement; 29, identifier:comments; 30, return_statement; 31, block; 32, identifier:Optional; 33, type_parameter; 34, identifier:self; 35, identifier:config; 36, string_content:ignore_comments; 37, subscript; 38, identifier:original_string; 39, return_statement; 40, type; 41, call; 42, integer:0; 43, call; 44, generic_type; 45, attribute; 46, argument_list; 47, attribute; 48, argument_list; 49, identifier:Sequence; 50, type_parameter; 51, identifier:self; 52, identifier:_strip_comments; 53, identifier:original_string; 54, string:"{0}{1} {2}"; 55, identifier:format; 56, subscript; 57, subscript; 58, call; 59, type; 60, call; 61, integer:0; 62, attribute; 63, string; 64, attribute; 65, argument_list; 66, identifier:str; 67, attribute; 68, argument_list; 69, identifier:self; 70, identifier:config; 71, string_content:comment_prefix; 72, string:"; "; 73, identifier:join; 74, identifier:comments; 75, identifier:self; 76, identifier:_strip_comments; 77, identifier:original_string | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 3, 7; 3, 8; 4, 9; 5, 10; 5, 11; 5, 12; 7, 13; 7, 14; 8, 15; 8, 16; 8, 17; 10, 18; 11, 19; 11, 20; 12, 21; 12, 22; 12, 23; 14, 24; 16, 25; 19, 26; 19, 27; 20, 28; 21, 29; 22, 30; 23, 31; 24, 32; 24, 33; 26, 34; 26, 35; 27, 36; 28, 37; 30, 38; 31, 39; 33, 40; 37, 41; 37, 42; 39, 43; 40, 44; 41, 45; 41, 46; 43, 47; 43, 48; 44, 49; 44, 50; 45, 51; 45, 52; 46, 53; 47, 54; 47, 55; 48, 56; 48, 57; 48, 58; 50, 59; 56, 60; 56, 61; 57, 62; 57, 63; 58, 64; 58, 65; 59, 66; 60, 67; 60, 68; 62, 69; 62, 70; 63, 71; 64, 72; 64, 73; 65, 74; 67, 75; 67, 76; 68, 77 | def _add_comments(
self,
comments: Optional[Sequence[str]],
original_string: str = ""
) -> str:
"""
Returns a string with comments added if ignore_comments is not set.
"""
if self.config['ignore_comments']:
return self._strip_comments(original_string)[0]
if not comments:
return original_string
else:
return "{0}{1} {2}".format(self._strip_comments(original_string)[0],
self.config['comment_prefix'],
"; ".join(comments)) |
0, module; 1, function_definition; 2, function_name:_wrap; 3, parameters; 4, type; 5, block; 6, identifier:self; 7, typed_parameter; 8, identifier:str; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, return_statement; 13, identifier:line; 14, type; 15, comment:"""
Returns an import wrapped to the specified line-length, if possible.
"""; 16, assignment; 17, boolean_operator; 18, block; 19, elif_clause; 20, identifier:line; 21, identifier:str; 22, identifier:wrap_mode; 23, subscript; 24, comparison_operator:len(line) > self.config['line_length']; 25, comparison_operator:wrap_mode != WrapModes.NOQA; 26, expression_statement; 27, expression_statement; 28, if_statement; 29, for_statement; 30, boolean_operator; 31, block; 32, attribute; 33, string; 34, call; 35, subscript; 36, identifier:wrap_mode; 37, attribute; 38, assignment; 39, assignment; 40, comparison_operator:'#' in line; 41, block; 42, identifier:splitter; 43, tuple; 44, block; 45, comparison_operator:len(line) > self.config['line_length']; 46, comparison_operator:wrap_mode == settings.WrapModes.NOQA; 47, if_statement; 48, identifier:self; 49, identifier:config; 50, string_content:multi_line_output; 51, identifier:len; 52, argument_list; 53, attribute; 54, string; 55, identifier:WrapModes; 56, identifier:NOQA; 57, identifier:line_without_comment; 58, identifier:line; 59, identifier:comment; 60, None; 61, string; 62, identifier:line; 63, expression_statement; 64, string:"import "; 65, string:"."; 66, string:"as "; 67, expression_statement; 68, if_statement; 69, call; 70, subscript; 71, identifier:wrap_mode; 72, attribute; 73, comparison_operator:"# NOQA" not in line; 74, block; 75, identifier:line; 76, identifier:self; 77, identifier:config; 78, string_content:line_length; 79, string_content:#; 80, assignment; 81, assignment; 82, boolean_operator; 83, block; 84, identifier:len; 85, argument_list; 86, attribute; 87, string; 88, attribute; 89, identifier:NOQA; 90, string:"# NOQA"; 91, identifier:line; 92, return_statement; 93, pattern_list; 94, call; 95, identifier:exp; 96, binary_operator:r"\b" + re.escape(splitter) + r"\b"; 97, call; 98, not_operator; 99, expression_statement; 100, if_statement; 101, expression_statement; 102, while_statement; 103, if_statement; 104, expression_statement; 105, if_statement; 106, return_statement; 107, identifier:line; 108, identifier:self; 109, identifier:config; 110, string_content:line_length; 111, identifier:settings; 112, identifier:WrapModes; 113, call; 114, identifier:line_without_comment; 115, identifier:comment; 116, attribute; 117, argument_list; 118, binary_operator:r"\b" + re.escape(splitter); 119, string:r"\b"; 120, attribute; 121, argument_list; 122, call; 123, assignment; 124, identifier:comment; 125, block; 126, assignment; 127, boolean_operator; 128, block; 129, not_operator; 130, block; 131, assignment; 132, subscript; 133, block; 134, call; 135, attribute; 136, argument_list; 137, identifier:line; 138, identifier:split; 139, string; 140, integer:1; 141, string:r"\b"; 142, call; 143, identifier:re; 144, identifier:search; 145, identifier:exp; 146, identifier:line_without_comment; 147, attribute; 148, argument_list; 149, identifier:line_parts; 150, call; 151, expression_statement; 152, identifier:next_line; 153, list; 154, comparison_operator:(len(line) + 2) > (self.config['wrap_length'] or self.config['line_length']); 155, identifier:line_parts; 156, expression_statement; 157, expression_statement; 158, identifier:line; 159, expression_statement; 160, identifier:cont_line; 161, call; 162, attribute; 163, string; 164, expression_statement; 165, expression_statement; 166, if_statement; 167, return_statement; 168, attribute; 169, argument_list; 170, string:"{0}{1} NOQA"; 171, identifier:format; 172, identifier:line; 173, subscript; 174, string_content:#; 175, attribute; 176, argument_list; 177, call; 178, identifier:startswith; 179, identifier:splitter; 180, attribute; 181, argument_list; 182, assignment; 183, parenthesized_expression; 184, parenthesized_expression; 185, call; 186, assignment; 187, assignment; 188, attribute; 189, argument_list; 190, identifier:self; 191, identifier:config; 192, string_content:use_parentheses; 193, assignment; 194, assignment; 195, boolean_operator; 196, block; 197, call; 198, string:"{0}{1}\\{2}{3}"; 199, identifier:format; 200, identifier:line; 201, identifier:splitter; 202, attribute; 203, identifier:cont_line; 204, attribute; 205, string; 206, identifier:re; 207, identifier:escape; 208, identifier:splitter; 209, attribute; 210, argument_list; 211, identifier:re; 212, identifier:split; 213, identifier:exp; 214, identifier:line_without_comment; 215, subscript; 216, call; 217, binary_operator:len(line) + 2; 218, boolean_operator; 219, attribute; 220, argument_list; 221, identifier:line; 222, call; 223, identifier:line; 224, call; 225, identifier:self; 226, identifier:_wrap; 227, binary_operator:self.config['indent'] + splitter.join(next_line).lstrip(); 228, identifier:output; 229, call; 230, identifier:lines; 231, call; 232, comparison_operator:self.config['comment_prefix'] in lines[-1]; 233, call; 234, expression_statement; 235, expression_statement; 236, attribute; 237, argument_list; 238, identifier:self; 239, identifier:line_separator; 240, identifier:self; 241, identifier:config; 242, string_content:comment_prefix; 243, identifier:line_without_comment; 244, identifier:strip; 245, identifier:line_parts; 246, unary_operator; 247, attribute; 248, argument_list; 249, call; 250, integer:2; 251, subscript; 252, subscript; 253, identifier:next_line; 254, identifier:append; 255, call; 256, attribute; 257, argument_list; 258, attribute; 259, argument_list; 260, subscript; 261, call; 262, attribute; 263, argument_list; 264, attribute; 265, argument_list; 266, subscript; 267, subscript; 268, attribute; 269, argument_list; 270, assignment; 271, assignment; 272, attribute; 273, identifier:join; 274, identifier:lines; 275, integer:1; 276, string; 277, identifier:format; 278, subscript; 279, identifier:comment; 280, identifier:len; 281, argument_list; 282, attribute; 283, string; 284, attribute; 285, string; 286, attribute; 287, argument_list; 288, identifier:splitter; 289, identifier:join; 290, identifier:line_parts; 291, identifier:next_line; 292, identifier:pop; 293, attribute; 294, string; 295, attribute; 296, argument_list; 297, string:"{0}{1}({2}{3}{4}{5})"; 298, identifier:format; 299, identifier:line; 300, identifier:splitter; 301, attribute; 302, identifier:cont_line; 303, conditional_expression:"," if self.config['include_trailing_comma'] else ""; 304, conditional_expression:self.line_separator if wrap_mode in {WrapModes.VERTICAL_HANGING_INDENT,
WrapModes.VERTICAL_GRID_GROUPED}
else ""; 305, identifier:output; 306, identifier:split; 307, attribute; 308, attribute; 309, string; 310, identifier:lines; 311, unary_operator; 312, subscript; 313, identifier:endswith; 314, string; 315, pattern_list; 316, call; 317, subscript; 318, binary_operator:line + ')' + self.config['comment_prefix'] + comment[:-1]; 319, identifier:self; 320, identifier:line_separator; 321, string_content:{0}#{1}; 322, identifier:line_parts; 323, unary_operator; 324, identifier:line; 325, identifier:self; 326, identifier:config; 327, string_content:wrap_length; 328, identifier:self; 329, identifier:config; 330, string_content:line_length; 331, identifier:line_parts; 332, identifier:pop; 333, identifier:self; 334, identifier:config; 335, string_content:indent; 336, call; 337, identifier:lstrip; 338, identifier:self; 339, identifier:line_separator; 340, string:","; 341, subscript; 342, string:""; 343, attribute; 344, comparison_operator:wrap_mode in {WrapModes.VERTICAL_HANGING_INDENT,
WrapModes.VERTICAL_GRID_GROUPED}; 345, string:""; 346, identifier:self; 347, identifier:line_separator; 348, identifier:self; 349, identifier:config; 350, string_content:comment_prefix; 351, integer:1; 352, identifier:lines; 353, unary_operator; 354, string_content:); 355, identifier:line; 356, identifier:comment; 357, attribute; 358, argument_list; 359, identifier:lines; 360, unary_operator; 361, binary_operator:line + ')' + self.config['comment_prefix']; 362, subscript; 363, integer:1; 364, attribute; 365, argument_list; 366, attribute; 367, string; 368, identifier:self; 369, identifier:line_separator; 370, identifier:wrap_mode; 371, set; 372, integer:1; 373, subscript; 374, identifier:split; 375, subscript; 376, integer:1; 377, integer:1; 378, binary_operator:line + ')'; 379, subscript; 380, identifier:comment; 381, slice; 382, identifier:splitter; 383, identifier:join; 384, identifier:next_line; 385, identifier:self; 386, identifier:config; 387, string_content:include_trailing_comma; 388, attribute; 389, attribute; 390, identifier:lines; 391, unary_operator; 392, attribute; 393, string; 394, identifier:line; 395, string; 396, attribute; 397, string; 398, unary_operator; 399, identifier:WrapModes; 400, identifier:VERTICAL_HANGING_INDENT; 401, identifier:WrapModes; 402, identifier:VERTICAL_GRID_GROUPED; 403, integer:1; 404, identifier:self; 405, identifier:config; 406, string_content:comment_prefix; 407, string_content:); 408, identifier:self; 409, identifier:config; 410, string_content:comment_prefix; 411, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 3, 7; 4, 8; 5, 9; 5, 10; 5, 11; 5, 12; 7, 13; 7, 14; 9, 15; 10, 16; 11, 17; 11, 18; 11, 19; 12, 20; 14, 21; 16, 22; 16, 23; 17, 24; 17, 25; 18, 26; 18, 27; 18, 28; 18, 29; 19, 30; 19, 31; 23, 32; 23, 33; 24, 34; 24, 35; 25, 36; 25, 37; 26, 38; 27, 39; 28, 40; 28, 41; 29, 42; 29, 43; 29, 44; 30, 45; 30, 46; 31, 47; 32, 48; 32, 49; 33, 50; 34, 51; 34, 52; 35, 53; 35, 54; 37, 55; 37, 56; 38, 57; 38, 58; 39, 59; 39, 60; 40, 61; 40, 62; 41, 63; 43, 64; 43, 65; 43, 66; 44, 67; 44, 68; 45, 69; 45, 70; 46, 71; 46, 72; 47, 73; 47, 74; 52, 75; 53, 76; 53, 77; 54, 78; 61, 79; 63, 80; 67, 81; 68, 82; 68, 83; 69, 84; 69, 85; 70, 86; 70, 87; 72, 88; 72, 89; 73, 90; 73, 91; 74, 92; 80, 93; 80, 94; 81, 95; 81, 96; 82, 97; 82, 98; 83, 99; 83, 100; 83, 101; 83, 102; 83, 103; 83, 104; 83, 105; 83, 106; 85, 107; 86, 108; 86, 109; 87, 110; 88, 111; 88, 112; 92, 113; 93, 114; 93, 115; 94, 116; 94, 117; 96, 118; 96, 119; 97, 120; 97, 121; 98, 122; 99, 123; 100, 124; 100, 125; 101, 126; 102, 127; 102, 128; 103, 129; 103, 130; 104, 131; 105, 132; 105, 133; 106, 134; 113, 135; 113, 136; 116, 137; 116, 138; 117, 139; 117, 140; 118, 141; 118, 142; 120, 143; 120, 144; 121, 145; 121, 146; 122, 147; 122, 148; 123, 149; 123, 150; 125, 151; 126, 152; 126, 153; 127, 154; 127, 155; 128, 156; 128, 157; 129, 158; 130, 159; 131, 160; 131, 161; 132, 162; 132, 163; 133, 164; 133, 165; 133, 166; 133, 167; 134, 168; 134, 169; 135, 170; 135, 171; 136, 172; 136, 173; 139, 174; 142, 175; 142, 176; 147, 177; 147, 178; 148, 179; 150, 180; 150, 181; 151, 182; 154, 183; 154, 184; 156, 185; 157, 186; 159, 187; 161, 188; 161, 189; 162, 190; 162, 191; 163, 192; 164, 193; 165, 194; 166, 195; 166, 196; 167, 197; 168, 198; 168, 199; 169, 200; 169, 201; 169, 202; 169, 203; 173, 204; 173, 205; 175, 206; 175, 207; 176, 208; 177, 209; 177, 210; 180, 211; 180, 212; 181, 213; 181, 214; 182, 215; 182, 216; 183, 217; 184, 218; 185, 219; 185, 220; 186, 221; 186, 222; 187, 223; 187, 224; 188, 225; 188, 226; 189, 227; 193, 228; 193, 229; 194, 230; 194, 231; 195, 232; 195, 233; 196, 234; 196, 235; 197, 236; 197, 237; 202, 238; 202, 239; 204, 240; 204, 241; 205, 242; 209, 243; 209, 244; 215, 245; 215, 246; 216, 247; 216, 248; 217, 249; 217, 250; 218, 251; 218, 252; 219, 253; 219, 254; 220, 255; 222, 256; 222, 257; 224, 258; 224, 259; 227, 260; 227, 261; 229, 262; 229, 263; 231, 264; 231, 265; 232, 266; 232, 267; 233, 268; 233, 269; 234, 270; 235, 271; 236, 272; 236, 273; 237, 274; 246, 275; 247, 276; 247, 277; 248, 278; 248, 279; 249, 280; 249, 281; 251, 282; 251, 283; 252, 284; 252, 285; 255, 286; 255, 287; 256, 288; 256, 289; 257, 290; 258, 291; 258, 292; 260, 293; 260, 294; 261, 295; 261, 296; 262, 297; 262, 298; 263, 299; 263, 300; 263, 301; 263, 302; 263, 303; 263, 304; 264, 305; 264, 306; 265, 307; 266, 308; 266, 309; 267, 310; 267, 311; 268, 312; 268, 313; 269, 314; 270, 315; 270, 316; 271, 317; 271, 318; 272, 319; 272, 320; 276, 321; 278, 322; 278, 323; 281, 324; 282, 325; 282, 326; 283, 327; 284, 328; 284, 329; 285, 330; 286, 331; 286, 332; 293, 333; 293, 334; 294, 335; 295, 336; 295, 337; 301, 338; 301, 339; 303, 340; 303, 341; 303, 342; 304, 343; 304, 344; 304, 345; 307, 346; 307, 347; 308, 348; 308, 349; 309, 350; 311, 351; 312, 352; 312, 353; 314, 354; 315, 355; 315, 356; 316, 357; 316, 358; 317, 359; 317, 360; 318, 361; 318, 362; 323, 363; 336, 364; 336, 365; 341, 366; 341, 367; 343, 368; 343, 369; 344, 370; 344, 371; 353, 372; 357, 373; 357, 374; 358, 375; 358, 376; 360, 377; 361, 378; 361, 379; 362, 380; 362, 381; 364, 382; 364, 383; 365, 384; 366, 385; 366, 386; 367, 387; 371, 388; 371, 389; 373, 390; 373, 391; 375, 392; 375, 393; 378, 394; 378, 395; 379, 396; 379, 397; 381, 398; 388, 399; 388, 400; 389, 401; 389, 402; 391, 403; 392, 404; 392, 405; 393, 406; 395, 407; 396, 408; 396, 409; 397, 410; 398, 411 | def _wrap(self, line: str) -> str:
"""
Returns an import wrapped to the specified line-length, if possible.
"""
wrap_mode = self.config['multi_line_output']
if len(line) > self.config['line_length'] and wrap_mode != WrapModes.NOQA:
line_without_comment = line
comment = None
if '#' in line:
line_without_comment, comment = line.split('#', 1)
for splitter in ("import ", ".", "as "):
exp = r"\b" + re.escape(splitter) + r"\b"
if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(splitter):
line_parts = re.split(exp, line_without_comment)
if comment:
line_parts[-1] = '{0}#{1}'.format(line_parts[-1], comment)
next_line = []
while (len(line) + 2) > (self.config['wrap_length'] or self.config['line_length']) and line_parts:
next_line.append(line_parts.pop())
line = splitter.join(line_parts)
if not line:
line = next_line.pop()
cont_line = self._wrap(self.config['indent'] + splitter.join(next_line).lstrip())
if self.config['use_parentheses']:
output = "{0}{1}({2}{3}{4}{5})".format(
line, splitter, self.line_separator, cont_line,
"," if self.config['include_trailing_comma'] else "",
self.line_separator if wrap_mode in {WrapModes.VERTICAL_HANGING_INDENT,
WrapModes.VERTICAL_GRID_GROUPED}
else "")
lines = output.split(self.line_separator)
if self.config['comment_prefix'] in lines[-1] and lines[-1].endswith(')'):
line, comment = lines[-1].split(self.config['comment_prefix'], 1)
lines[-1] = line + ')' + self.config['comment_prefix'] + comment[:-1]
return self.line_separator.join(lines)
return "{0}{1}\\{2}{3}".format(line, splitter, self.line_separator, cont_line)
elif len(line) > self.config['line_length'] and wrap_mode == settings.WrapModes.NOQA:
if "# NOQA" not in line:
return "{0}{1} NOQA".format(line, self.config['comment_prefix'])
return line |
0, module; 1, function_definition; 2, function_name:get_formatter; 3, parameters; 4, block; 5, identifier:name; 6, expression_statement; 7, for_statement; 8, comment:"""
Looks up a formatter class given a prefix to it.
The names are sorted, and the first matching class is returned.
"""; 9, identifier:k; 10, call; 11, block; 12, identifier:sorted; 13, argument_list; 14, if_statement; 15, identifier:_FORMATTERS; 16, call; 17, block; 18, attribute; 19, argument_list; 20, return_statement; 21, identifier:k; 22, identifier:startswith; 23, identifier:name; 24, subscript; 25, identifier:_FORMATTERS; 26, identifier:k | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 7, 10; 7, 11; 10, 12; 10, 13; 11, 14; 13, 15; 14, 16; 14, 17; 16, 18; 16, 19; 17, 20; 18, 21; 18, 22; 19, 23; 20, 24; 24, 25; 24, 26 | def get_formatter(name):
"""
Looks up a formatter class given a prefix to it.
The names are sorted, and the first matching class is returned.
"""
for k in sorted(_FORMATTERS):
if k.startswith(name):
return _FORMATTERS[k] |
0, module; 1, function_definition; 2, function_name:call_once; 3, parameters; 4, block; 5, identifier:func; 6, expression_statement; 7, expression_statement; 8, if_statement; 9, decorated_definition; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, comment:"""Decorate a function to only allow it to be called once.
Note that it doesn't make sense to only call a function once if it takes
arguments (use @functools.lru_cache for that sort of thing), so this only
works on callables that take no args.
"""; 15, assignment; 16, boolean_operator; 17, block; 18, decorator; 19, function_definition; 20, assignment; 21, assignment; 22, assignment; 23, identifier:_wrapper; 24, identifier:argspec; 25, call; 26, boolean_operator; 27, attribute; 28, raise_statement; 29, call; 30, function_name:_wrapper; 31, parameters; 32, comment:# If we haven't been called yet, actually invoke func and save the result.; 33, block; 34, attribute; 35, False; 36, attribute; 37, lambda; 38, attribute; 39, lambda; 40, attribute; 41, argument_list; 42, attribute; 43, attribute; 44, identifier:argspec; 45, identifier:keywords; 46, call; 47, attribute; 48, argument_list; 49, if_statement; 50, return_statement; 51, identifier:_wrapper; 52, identifier:has_run; 53, identifier:_wrapper; 54, identifier:HasRun; 55, attribute; 56, identifier:_wrapper; 57, identifier:MarkAsRun; 58, call; 59, identifier:inspect; 60, identifier:getargspec; 61, identifier:func; 62, identifier:argspec; 63, identifier:args; 64, identifier:argspec; 65, identifier:varargs; 66, identifier:ValueError; 67, argument_list; 68, identifier:functools; 69, identifier:wraps; 70, identifier:func; 71, not_operator; 72, block; 73, attribute; 74, identifier:_wrapper; 75, identifier:has_run; 76, identifier:setattr; 77, argument_list; 78, string; 79, identifier:func; 80, identifier:argspec; 81, call; 82, expression_statement; 83, expression_statement; 84, identifier:_wrapper; 85, identifier:return_value; 86, identifier:_wrapper; 87, string; 88, True; 89, string_content:Can only decorate functions with no args; 90, attribute; 91, argument_list; 92, call; 93, assignment; 94, string_content:has_run; 95, identifier:_wrapper; 96, identifier:HasRun; 97, attribute; 98, argument_list; 99, attribute; 100, call; 101, identifier:_wrapper; 102, identifier:MarkAsRun; 103, identifier:_wrapper; 104, identifier:return_value; 105, identifier:func; 106, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 7, 15; 8, 16; 8, 17; 9, 18; 9, 19; 10, 20; 11, 21; 12, 22; 13, 23; 15, 24; 15, 25; 16, 26; 16, 27; 17, 28; 18, 29; 19, 30; 19, 31; 19, 32; 19, 33; 20, 34; 20, 35; 21, 36; 21, 37; 22, 38; 22, 39; 25, 40; 25, 41; 26, 42; 26, 43; 27, 44; 27, 45; 28, 46; 29, 47; 29, 48; 33, 49; 33, 50; 34, 51; 34, 52; 36, 53; 36, 54; 37, 55; 38, 56; 38, 57; 39, 58; 40, 59; 40, 60; 41, 61; 42, 62; 42, 63; 43, 64; 43, 65; 46, 66; 46, 67; 47, 68; 47, 69; 48, 70; 49, 71; 49, 72; 50, 73; 55, 74; 55, 75; 58, 76; 58, 77; 67, 78; 67, 79; 67, 80; 71, 81; 72, 82; 72, 83; 73, 84; 73, 85; 77, 86; 77, 87; 77, 88; 78, 89; 81, 90; 81, 91; 82, 92; 83, 93; 87, 94; 90, 95; 90, 96; 92, 97; 92, 98; 93, 99; 93, 100; 97, 101; 97, 102; 99, 103; 99, 104; 100, 105; 100, 106 | def call_once(func):
"""Decorate a function to only allow it to be called once.
Note that it doesn't make sense to only call a function once if it takes
arguments (use @functools.lru_cache for that sort of thing), so this only
works on callables that take no args.
"""
argspec = inspect.getargspec(func)
if argspec.args or argspec.varargs or argspec.keywords:
raise ValueError('Can only decorate functions with no args', func, argspec)
@functools.wraps(func)
def _wrapper():
# If we haven't been called yet, actually invoke func and save the result.
if not _wrapper.HasRun():
_wrapper.MarkAsRun()
_wrapper.return_value = func()
return _wrapper.return_value
_wrapper.has_run = False
_wrapper.HasRun = lambda: _wrapper.has_run
_wrapper.MarkAsRun = lambda: setattr(_wrapper, 'has_run', True)
return _wrapper |
0, module; 1, function_definition; 2, function_name:paginate; 3, parameters; 4, block; 5, identifier:self; 6, identifier:model_class; 7, identifier:order_by; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, if_statement; 16, expression_statement; 17, expression_statement; 18, if_statement; 19, expression_statement; 20, expression_statement; 21, expression_statement; 22, return_statement; 23, identifier:page_num; 24, integer:1; 25, identifier:page_size; 26, integer:100; 27, identifier:conditions; 28, None; 29, identifier:settings; 30, None; 31, string; 32, assignment; 33, assignment; 34, comparison_operator:page_num == -1; 35, block; 36, elif_clause; 37, assignment; 38, assignment; 39, identifier:conditions; 40, block; 41, augmented_assignment; 42, augmented_assignment; 43, assignment; 44, call; 45, string_content:Selects records and returns a single page of model instances.
- `model_class`: the model class matching the query's table,
or `None` for getting back instances of an ad-hoc model.
- `order_by`: columns to use for sorting the query (contents of the ORDER BY clause).
- `page_num`: the page number (1-based), or -1 to get the last page.
- `page_size`: number of records to return per page.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
- `settings`: query settings to send as HTTP GET parameters
The result is a namedtuple containing `objects` (list), `number_of_objects`,
`pages_total`, `number` (of the current page), and `page_size`.; 46, identifier:count; 47, call; 48, identifier:pages_total; 49, call; 50, identifier:page_num; 51, unary_operator; 52, expression_statement; 53, comparison_operator:page_num < 1; 54, block; 55, identifier:offset; 56, binary_operator:(page_num - 1) * page_size; 57, identifier:query; 58, string; 59, expression_statement; 60, identifier:query; 61, binary_operator:' ORDER BY %s' % order_by; 62, identifier:query; 63, binary_operator:' LIMIT %d, %d' % (offset, page_size); 64, identifier:query; 65, call; 66, identifier:Page; 67, argument_list; 68, attribute; 69, argument_list; 70, identifier:int; 71, argument_list; 72, integer:1; 73, assignment; 74, identifier:page_num; 75, integer:1; 76, raise_statement; 77, parenthesized_expression; 78, identifier:page_size; 79, string_content:SELECT * FROM $table; 80, augmented_assignment; 81, string; 82, identifier:order_by; 83, string; 84, tuple; 85, attribute; 86, argument_list; 87, keyword_argument; 88, keyword_argument; 89, keyword_argument; 90, keyword_argument; 91, keyword_argument; 92, identifier:self; 93, identifier:count; 94, identifier:model_class; 95, identifier:conditions; 96, call; 97, identifier:page_num; 98, call; 99, call; 100, binary_operator:page_num - 1; 101, identifier:query; 102, binary_operator:' WHERE ' + conditions; 103, string_content:ORDER BY %s; 104, string_content:LIMIT %d, %d; 105, identifier:offset; 106, identifier:page_size; 107, identifier:self; 108, identifier:_substitute; 109, identifier:query; 110, identifier:model_class; 111, identifier:objects; 112, conditional_expression:list(self.select(query, model_class, settings)) if count else []; 113, identifier:number_of_objects; 114, identifier:count; 115, identifier:pages_total; 116, identifier:pages_total; 117, identifier:number; 118, identifier:page_num; 119, identifier:page_size; 120, identifier:page_size; 121, identifier:ceil; 122, argument_list; 123, identifier:max; 124, argument_list; 125, identifier:ValueError; 126, argument_list; 127, identifier:page_num; 128, integer:1; 129, string; 130, identifier:conditions; 131, call; 132, identifier:count; 133, list; 134, binary_operator:count / float(page_size); 135, identifier:pages_total; 136, integer:1; 137, binary_operator:'Invalid page number: %d' % page_num; 138, string_content:WHERE; 139, identifier:list; 140, argument_list; 141, identifier:count; 142, call; 143, string; 144, identifier:page_num; 145, call; 146, identifier:float; 147, argument_list; 148, string_content:Invalid page number: %d; 149, attribute; 150, argument_list; 151, identifier:page_size; 152, identifier:self; 153, identifier:select; 154, identifier:query; 155, identifier:model_class; 156, identifier:settings | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 8, 23; 8, 24; 9, 25; 9, 26; 10, 27; 10, 28; 11, 29; 11, 30; 12, 31; 13, 32; 14, 33; 15, 34; 15, 35; 15, 36; 16, 37; 17, 38; 18, 39; 18, 40; 19, 41; 20, 42; 21, 43; 22, 44; 31, 45; 32, 46; 32, 47; 33, 48; 33, 49; 34, 50; 34, 51; 35, 52; 36, 53; 36, 54; 37, 55; 37, 56; 38, 57; 38, 58; 40, 59; 41, 60; 41, 61; 42, 62; 42, 63; 43, 64; 43, 65; 44, 66; 44, 67; 47, 68; 47, 69; 49, 70; 49, 71; 51, 72; 52, 73; 53, 74; 53, 75; 54, 76; 56, 77; 56, 78; 58, 79; 59, 80; 61, 81; 61, 82; 63, 83; 63, 84; 65, 85; 65, 86; 67, 87; 67, 88; 67, 89; 67, 90; 67, 91; 68, 92; 68, 93; 69, 94; 69, 95; 71, 96; 73, 97; 73, 98; 76, 99; 77, 100; 80, 101; 80, 102; 81, 103; 83, 104; 84, 105; 84, 106; 85, 107; 85, 108; 86, 109; 86, 110; 87, 111; 87, 112; 88, 113; 88, 114; 89, 115; 89, 116; 90, 117; 90, 118; 91, 119; 91, 120; 96, 121; 96, 122; 98, 123; 98, 124; 99, 125; 99, 126; 100, 127; 100, 128; 102, 129; 102, 130; 112, 131; 112, 132; 112, 133; 122, 134; 124, 135; 124, 136; 126, 137; 129, 138; 131, 139; 131, 140; 134, 141; 134, 142; 137, 143; 137, 144; 140, 145; 142, 146; 142, 147; 143, 148; 145, 149; 145, 150; 147, 151; 149, 152; 149, 153; 150, 154; 150, 155; 150, 156 | def paginate(self, model_class, order_by, page_num=1, page_size=100, conditions=None, settings=None):
'''
Selects records and returns a single page of model instances.
- `model_class`: the model class matching the query's table,
or `None` for getting back instances of an ad-hoc model.
- `order_by`: columns to use for sorting the query (contents of the ORDER BY clause).
- `page_num`: the page number (1-based), or -1 to get the last page.
- `page_size`: number of records to return per page.
- `conditions`: optional SQL conditions (contents of the WHERE clause).
- `settings`: query settings to send as HTTP GET parameters
The result is a namedtuple containing `objects` (list), `number_of_objects`,
`pages_total`, `number` (of the current page), and `page_size`.
'''
count = self.count(model_class, conditions)
pages_total = int(ceil(count / float(page_size)))
if page_num == -1:
page_num = max(pages_total, 1)
elif page_num < 1:
raise ValueError('Invalid page number: %d' % page_num)
offset = (page_num - 1) * page_size
query = 'SELECT * FROM $table'
if conditions:
query += ' WHERE ' + conditions
query += ' ORDER BY %s' % order_by
query += ' LIMIT %d, %d' % (offset, page_size)
query = self._substitute(query, model_class)
return Page(
objects=list(self.select(query, model_class, settings)) if count else [],
number_of_objects=count,
pages_total=pages_total,
number=page_num,
page_size=page_size
) |
0, module; 1, function_definition; 2, function_name:compute_memory_contents_under_schedule; 3, parameters; 4, block; 5, identifier:self; 6, identifier:schedule; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, return_statement; 13, comment:"""The in-memory tensors present when executing each operation in schedule.
Simulates running operations in the order given by a schedule. Keeps track
of the tensors in memory at every point in time, and outputs a list (one
entry for each point in time) of all sets of all memory contents (i.e. a
frozenset of strings) ever seen in this execution.
It is assumed (but not checked) that schedule is a valid topological sort of
the operations in this graph.
Args:
schedule: A list of integer ids; the order to run operations in.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
get_all_operation_names()).
"""; 14, assignment; 15, assignment; 16, assignment; 17, identifier:operation_id; 18, identifier:schedule; 19, block; 20, identifier:memory_contents_for_each_operation; 21, identifier:out_degree; 22, call; 23, identifier:curr_memory_contents; 24, call; 25, identifier:memory_contents_for_each_operation; 26, list; 27, expression_statement; 28, comment:# Allocate new memory to perform the computation at this node.; 29, for_statement; 30, expression_statement; 31, comment:# Free any tensors which are no longer needed.; 32, for_statement; 33, for_statement; 34, attribute; 35, argument_list; 36, identifier:set; 37, argument_list; 38, assignment; 39, identifier:output_name; 40, call; 41, block; 42, call; 43, identifier:output_name; 44, call; 45, block; 46, identifier:input_name; 47, call; 48, block; 49, identifier:self; 50, identifier:_compute_initial_out_degree; 51, identifier:operation_name; 52, attribute; 53, attribute; 54, argument_list; 55, expression_statement; 56, attribute; 57, argument_list; 58, attribute; 59, argument_list; 60, if_statement; 61, attribute; 62, argument_list; 63, expression_statement; 64, if_statement; 65, subscript; 66, identifier:name; 67, identifier:self; 68, identifier:get_operation_output_names; 69, identifier:operation_name; 70, call; 71, identifier:memory_contents_for_each_operation; 72, identifier:append; 73, call; 74, identifier:self; 75, identifier:get_operation_output_names; 76, identifier:operation_name; 77, comparison_operator:out_degree[output_name] == 0; 78, block; 79, identifier:self; 80, identifier:get_operation_input_names; 81, identifier:operation_name; 82, augmented_assignment; 83, comparison_operator:out_degree[input_name] == 0; 84, block; 85, attribute; 86, identifier:operation_id; 87, attribute; 88, argument_list; 89, identifier:frozenset; 90, argument_list; 91, subscript; 92, integer:0; 93, expression_statement; 94, subscript; 95, integer:1; 96, subscript; 97, integer:0; 98, expression_statement; 99, identifier:self; 100, identifier:_operations; 101, identifier:curr_memory_contents; 102, identifier:add; 103, identifier:output_name; 104, identifier:curr_memory_contents; 105, identifier:out_degree; 106, identifier:output_name; 107, call; 108, identifier:out_degree; 109, identifier:input_name; 110, identifier:out_degree; 111, identifier:input_name; 112, call; 113, attribute; 114, argument_list; 115, attribute; 116, argument_list; 117, identifier:curr_memory_contents; 118, identifier:remove; 119, identifier:output_name; 120, identifier:curr_memory_contents; 121, identifier:remove; 122, identifier:input_name | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 8, 14; 9, 15; 10, 16; 11, 17; 11, 18; 11, 19; 12, 20; 14, 21; 14, 22; 15, 23; 15, 24; 16, 25; 16, 26; 19, 27; 19, 28; 19, 29; 19, 30; 19, 31; 19, 32; 19, 33; 22, 34; 22, 35; 24, 36; 24, 37; 27, 38; 29, 39; 29, 40; 29, 41; 30, 42; 32, 43; 32, 44; 32, 45; 33, 46; 33, 47; 33, 48; 34, 49; 34, 50; 38, 51; 38, 52; 40, 53; 40, 54; 41, 55; 42, 56; 42, 57; 44, 58; 44, 59; 45, 60; 47, 61; 47, 62; 48, 63; 48, 64; 52, 65; 52, 66; 53, 67; 53, 68; 54, 69; 55, 70; 56, 71; 56, 72; 57, 73; 58, 74; 58, 75; 59, 76; 60, 77; 60, 78; 61, 79; 61, 80; 62, 81; 63, 82; 64, 83; 64, 84; 65, 85; 65, 86; 70, 87; 70, 88; 73, 89; 73, 90; 77, 91; 77, 92; 78, 93; 82, 94; 82, 95; 83, 96; 83, 97; 84, 98; 85, 99; 85, 100; 87, 101; 87, 102; 88, 103; 90, 104; 91, 105; 91, 106; 93, 107; 94, 108; 94, 109; 96, 110; 96, 111; 98, 112; 107, 113; 107, 114; 112, 115; 112, 116; 113, 117; 113, 118; 114, 119; 115, 120; 115, 121; 116, 122 | def compute_memory_contents_under_schedule(self, schedule):
"""The in-memory tensors present when executing each operation in schedule.
Simulates running operations in the order given by a schedule. Keeps track
of the tensors in memory at every point in time, and outputs a list (one
entry for each point in time) of all sets of all memory contents (i.e. a
frozenset of strings) ever seen in this execution.
It is assumed (but not checked) that schedule is a valid topological sort of
the operations in this graph.
Args:
schedule: A list of integer ids; the order to run operations in.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
get_all_operation_names()).
"""
out_degree = self._compute_initial_out_degree()
curr_memory_contents = set()
memory_contents_for_each_operation = []
for operation_id in schedule:
operation_name = self._operations[operation_id].name
# Allocate new memory to perform the computation at this node.
for output_name in self.get_operation_output_names(operation_name):
curr_memory_contents.add(output_name)
memory_contents_for_each_operation.append(frozenset(curr_memory_contents))
# Free any tensors which are no longer needed.
for output_name in self.get_operation_output_names(operation_name):
if out_degree[output_name] == 0:
curr_memory_contents.remove(output_name)
for input_name in self.get_operation_input_names(operation_name):
out_degree[input_name] -= 1
if out_degree[input_name] == 0:
curr_memory_contents.remove(input_name)
return memory_contents_for_each_operation |
0, module; 1, function_definition; 2, function_name:sort; 3, parameters; 4, type; 5, block; 6, identifier:self; 7, typed_parameter; 8, typed_default_parameter; 9, dictionary_splat_pattern; 10, string; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, if_statement; 15, if_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, if_statement; 21, expression_statement; 22, if_statement; 23, if_statement; 24, if_statement; 25, identifier:by; 26, type; 27, identifier:out; 28, type; 29, string; 30, identifier:kwargs; 31, string_content:SASdata; 32, comment:"""
Sort the SAS Data Set
:param by: REQUIRED variable to sort by (BY <DESCENDING> variable-1 <<DESCENDING> variable-2 ...>;)
:param out: OPTIONAL takes either a string 'libref.table' or 'table' which will go to WORK or USER
if assigned or a sas data object'' will sort in place if allowed
:param kwargs:
:return: SASdata object if out= not specified, or a new SASdata object for out= when specified
:Example:
#. wkcars.sort('type')
#. wkcars2 = sas.sasdata('cars2')
#. wkcars.sort('cylinders', wkcars2)
#. cars2=cars.sort('DESCENDING origin', out='foobar')
#. cars.sort('type').head()
#. stat_results = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type'))
#. stat_results2 = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type','work.cars'))
"""; 33, assignment; 34, assignment; 35, identifier:out; 36, block; 37, comparison_operator:'options' in kwargs; 38, block; 39, assignment; 40, augmented_assignment; 41, augmented_assignment; 42, assignment; 43, attribute; 44, block; 45, assignment; 46, identifier:ll; 47, block; 48, identifier:runcode; 49, block; 50, identifier:out; 51, block; 52, else_clause; 53, identifier:str; 54, identifier:object; 55, identifier:outstr; 56, string; 57, identifier:options; 58, string; 59, if_statement; 60, string; 61, identifier:kwargs; 62, expression_statement; 63, identifier:code; 64, binary_operator:"proc sort data=%s.%s%s %s %s ;\n" % (self.libref, self.table, self._dsopts(), outstr, options); 65, identifier:code; 66, binary_operator:"by %s;" % by; 67, identifier:code; 68, string:"run\n;"; 69, identifier:runcode; 70, True; 71, attribute; 72, identifier:nosub; 73, expression_statement; 74, expression_statement; 75, identifier:ll; 76, call; 77, expression_statement; 78, expression_statement; 79, expression_statement; 80, for_statement; 81, if_statement; 82, if_statement; 83, block; 84, call; 85, block; 86, else_clause; 87, string_content:options; 88, assignment; 89, string:"proc sort data=%s.%s%s %s %s ;\n"; 90, tuple; 91, string:"by %s;"; 92, identifier:by; 93, identifier:self; 94, identifier:sas; 95, call; 96, assignment; 97, attribute; 98, argument_list; 99, assignment; 100, assignment; 101, assignment; 102, identifier:line; 103, call; 104, block; 105, call; 106, block; 107, not_operator; 108, block; 109, else_clause; 110, return_statement; 111, identifier:isinstance; 112, argument_list; 113, expression_statement; 114, if_statement; 115, block; 116, identifier:options; 117, subscript; 118, attribute; 119, attribute; 120, call; 121, identifier:outstr; 122, identifier:options; 123, identifier:print; 124, argument_list; 125, identifier:runcode; 126, False; 127, identifier:self; 128, identifier:_is_valid; 129, identifier:runcode; 130, False; 131, identifier:ll; 132, call; 133, identifier:elog; 134, list; 135, attribute; 136, argument_list; 137, if_statement; 138, identifier:len; 139, argument_list; 140, raise_statement; 141, call; 142, return_statement; 143, block; 144, identifier:self; 145, identifier:out; 146, identifier:str; 147, assignment; 148, comparison_operator:fn[1] == '.'; 149, block; 150, else_clause; 151, expression_statement; 152, expression_statement; 153, expression_statement; 154, identifier:kwargs; 155, string; 156, identifier:self; 157, identifier:libref; 158, identifier:self; 159, identifier:table; 160, attribute; 161, argument_list; 162, identifier:code; 163, attribute; 164, argument_list; 165, subscript; 166, identifier:splitlines; 167, call; 168, block; 169, identifier:elog; 170, call; 171, identifier:isinstance; 172, argument_list; 173, identifier:out; 174, return_statement; 175, identifier:fn; 176, call; 177, subscript; 178, string; 179, expression_statement; 180, expression_statement; 181, expression_statement; 182, block; 183, assignment; 184, assignment; 185, assignment; 186, string_content:options; 187, identifier:self; 188, identifier:_dsopts; 189, attribute; 190, identifier:submit; 191, identifier:code; 192, string:"text"; 193, identifier:ll; 194, string; 195, attribute; 196, argument_list; 197, expression_statement; 198, identifier:RuntimeError; 199, argument_list; 200, identifier:out; 201, identifier:str; 202, call; 203, attribute; 204, argument_list; 205, identifier:fn; 206, integer:1; 207, string_content:.; 208, assignment; 209, assignment; 210, assignment; 211, expression_statement; 212, expression_statement; 213, expression_statement; 214, identifier:libref; 215, attribute; 216, identifier:table; 217, attribute; 218, identifier:outstr; 219, binary_operator:"out=%s.%s" % (out.libref, out.table); 220, identifier:self; 221, identifier:sas; 222, string_content:LOG; 223, identifier:line; 224, identifier:startswith; 225, string; 226, call; 227, call; 228, attribute; 229, argument_list; 230, identifier:out; 231, identifier:partition; 232, string; 233, identifier:libref; 234, subscript; 235, identifier:table; 236, subscript; 237, identifier:outstr; 238, binary_operator:"out=%s.%s" % (libref, table); 239, assignment; 240, assignment; 241, assignment; 242, identifier:out; 243, identifier:libref; 244, identifier:out; 245, identifier:table; 246, string:"out=%s.%s"; 247, tuple; 248, string_content:ERROR; 249, attribute; 250, argument_list; 251, attribute; 252, argument_list; 253, attribute; 254, identifier:sasdata; 255, identifier:table; 256, identifier:libref; 257, attribute; 258, string_content:.; 259, identifier:fn; 260, integer:0; 261, identifier:fn; 262, integer:2; 263, string:"out=%s.%s"; 264, tuple; 265, identifier:libref; 266, string; 267, identifier:table; 268, subscript; 269, identifier:outstr; 270, binary_operator:"out=" + table; 271, attribute; 272, attribute; 273, identifier:elog; 274, identifier:append; 275, identifier:line; 276, string:"\n"; 277, identifier:join; 278, identifier:elog; 279, identifier:self; 280, identifier:sas; 281, identifier:self; 282, identifier:results; 283, identifier:libref; 284, identifier:table; 285, identifier:fn; 286, integer:0; 287, string:"out="; 288, identifier:table; 289, identifier:out; 290, identifier:libref; 291, identifier:out; 292, identifier:table | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 5, 11; 5, 12; 5, 13; 5, 14; 5, 15; 5, 16; 5, 17; 5, 18; 5, 19; 5, 20; 5, 21; 5, 22; 5, 23; 5, 24; 7, 25; 7, 26; 8, 27; 8, 28; 8, 29; 9, 30; 10, 31; 11, 32; 12, 33; 13, 34; 14, 35; 14, 36; 15, 37; 15, 38; 16, 39; 17, 40; 18, 41; 19, 42; 20, 43; 20, 44; 21, 45; 22, 46; 22, 47; 23, 48; 23, 49; 24, 50; 24, 51; 24, 52; 26, 53; 28, 54; 33, 55; 33, 56; 34, 57; 34, 58; 36, 59; 37, 60; 37, 61; 38, 62; 39, 63; 39, 64; 40, 65; 40, 66; 41, 67; 41, 68; 42, 69; 42, 70; 43, 71; 43, 72; 44, 73; 44, 74; 45, 75; 45, 76; 47, 77; 49, 78; 49, 79; 49, 80; 49, 81; 51, 82; 52, 83; 59, 84; 59, 85; 59, 86; 60, 87; 62, 88; 64, 89; 64, 90; 66, 91; 66, 92; 71, 93; 71, 94; 73, 95; 74, 96; 76, 97; 76, 98; 77, 99; 78, 100; 79, 101; 80, 102; 80, 103; 80, 104; 81, 105; 81, 106; 82, 107; 82, 108; 82, 109; 83, 110; 84, 111; 84, 112; 85, 113; 85, 114; 86, 115; 88, 116; 88, 117; 90, 118; 90, 119; 90, 120; 90, 121; 90, 122; 95, 123; 95, 124; 96, 125; 96, 126; 97, 127; 97, 128; 99, 129; 99, 130; 100, 131; 100, 132; 101, 133; 101, 134; 103, 135; 103, 136; 104, 137; 105, 138; 105, 139; 106, 140; 107, 141; 108, 142; 109, 143; 110, 144; 112, 145; 112, 146; 113, 147; 114, 148; 114, 149; 114, 150; 115, 151; 115, 152; 115, 153; 117, 154; 117, 155; 118, 156; 118, 157; 119, 158; 119, 159; 120, 160; 120, 161; 124, 162; 132, 163; 132, 164; 135, 165; 135, 166; 137, 167; 137, 168; 139, 169; 140, 170; 141, 171; 141, 172; 142, 173; 143, 174; 147, 175; 147, 176; 148, 177; 148, 178; 149, 179; 149, 180; 149, 181; 150, 182; 151, 183; 152, 184; 153, 185; 155, 186; 160, 187; 160, 188; 163, 189; 163, 190; 164, 191; 164, 192; 165, 193; 165, 194; 167, 195; 167, 196; 168, 197; 170, 198; 170, 199; 172, 200; 172, 201; 174, 202; 176, 203; 176, 204; 177, 205; 177, 206; 178, 207; 179, 208; 180, 209; 181, 210; 182, 211; 182, 212; 182, 213; 183, 214; 183, 215; 184, 216; 184, 217; 185, 218; 185, 219; 189, 220; 189, 221; 194, 222; 195, 223; 195, 224; 196, 225; 197, 226; 199, 227; 202, 228; 202, 229; 203, 230; 203, 231; 204, 232; 208, 233; 208, 234; 209, 235; 209, 236; 210, 237; 210, 238; 211, 239; 212, 240; 213, 241; 215, 242; 215, 243; 217, 244; 217, 245; 219, 246; 219, 247; 225, 248; 226, 249; 226, 250; 227, 251; 227, 252; 228, 253; 228, 254; 229, 255; 229, 256; 229, 257; 232, 258; 234, 259; 234, 260; 236, 261; 236, 262; 238, 263; 238, 264; 239, 265; 239, 266; 240, 267; 240, 268; 241, 269; 241, 270; 247, 271; 247, 272; 249, 273; 249, 274; 250, 275; 251, 276; 251, 277; 252, 278; 253, 279; 253, 280; 257, 281; 257, 282; 264, 283; 264, 284; 268, 285; 268, 286; 270, 287; 270, 288; 271, 289; 271, 290; 272, 291; 272, 292 | def sort(self, by: str, out: object = '', **kwargs) -> 'SASdata':
"""
Sort the SAS Data Set
:param by: REQUIRED variable to sort by (BY <DESCENDING> variable-1 <<DESCENDING> variable-2 ...>;)
:param out: OPTIONAL takes either a string 'libref.table' or 'table' which will go to WORK or USER
if assigned or a sas data object'' will sort in place if allowed
:param kwargs:
:return: SASdata object if out= not specified, or a new SASdata object for out= when specified
:Example:
#. wkcars.sort('type')
#. wkcars2 = sas.sasdata('cars2')
#. wkcars.sort('cylinders', wkcars2)
#. cars2=cars.sort('DESCENDING origin', out='foobar')
#. cars.sort('type').head()
#. stat_results = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type'))
#. stat_results2 = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type','work.cars'))
"""
outstr = ''
options = ''
if out:
if isinstance(out, str):
fn = out.partition('.')
if fn[1] == '.':
libref = fn[0]
table = fn[2]
outstr = "out=%s.%s" % (libref, table)
else:
libref = ''
table = fn[0]
outstr = "out=" + table
else:
libref = out.libref
table = out.table
outstr = "out=%s.%s" % (out.libref, out.table)
if 'options' in kwargs:
options = kwargs['options']
code = "proc sort data=%s.%s%s %s %s ;\n" % (self.libref, self.table, self._dsopts(), outstr, options)
code += "by %s;" % by
code += "run\n;"
runcode = True
if self.sas.nosub:
print(code)
runcode = False
ll = self._is_valid()
if ll:
runcode = False
if runcode:
ll = self.sas.submit(code, "text")
elog = []
for line in ll['LOG'].splitlines():
if line.startswith('ERROR'):
elog.append(line)
if len(elog):
raise RuntimeError("\n".join(elog))
if out:
if not isinstance(out, str):
return out
else:
return self.sas.sasdata(table, libref, self.results)
else:
return self |
0, module; 1, function_definition; 2, function_name:find_items; 3, parameters; 4, block; 5, identifier:self; 6, identifier:q; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, default_parameter; 14, default_parameter; 15, expression_statement; 16, if_statement; 17, if_statement; 18, if_statement; 19, if_statement; 20, if_statement; 21, comment:# Build up any restrictions; 22, if_statement; 23, expression_statement; 24, expression_statement; 25, if_statement; 26, identifier:shape; 27, identifier:ID_ONLY; 28, identifier:depth; 29, identifier:SHALLOW; 30, identifier:additional_fields; 31, None; 32, identifier:order_fields; 33, None; 34, identifier:calendar_view; 35, None; 36, identifier:page_size; 37, None; 38, identifier:max_items; 39, None; 40, identifier:offset; 41, integer:0; 42, comment:"""
Private method to call the FindItem service
:param q: a Q instance containing any restrictions
:param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is
non-null, we always return Item objects.
:param depth: controls the whether to return soft-deleted items or not.
:param additional_fields: the extra properties we want on the return objects. Default is no properties. Be
aware that complex fields can only be fetched with fetch() (i.e. the GetItem service).
:param order_fields: the SortOrder fields, if any
:param calendar_view: a CalendarView instance, if any
:param page_size: the requested number of items per page
:param max_items: the max number of items to return
:param offset: the offset relative to the first item in the item collection
:return: a generator for the returned item IDs or items
"""; 43, comparison_operator:shape not in SHAPE_CHOICES; 44, block; 45, comparison_operator:depth not in ITEM_TRAVERSAL_CHOICES; 46, block; 47, not_operator; 48, block; 49, identifier:additional_fields; 50, block; 51, boolean_operator; 52, block; 53, call; 54, block; 55, elif_clause; 56, else_clause; 57, call; 58, assignment; 59, boolean_operator; 60, block; 61, else_clause; 62, identifier:shape; 63, identifier:SHAPE_CHOICES; 64, raise_statement; 65, identifier:depth; 66, identifier:ITEM_TRAVERSAL_CHOICES; 67, raise_statement; 68, attribute; 69, expression_statement; 70, return_statement; 71, for_statement; 72, for_statement; 73, comparison_operator:calendar_view is not None; 74, not_operator; 75, raise_statement; 76, attribute; 77, argument_list; 78, expression_statement; 79, expression_statement; 80, attribute; 81, block; 82, block; 83, attribute; 84, argument_list; 85, identifier:items; 86, call; 87, comparison_operator:shape == ID_ONLY; 88, comparison_operator:additional_fields is None; 89, for_statement; 90, block; 91, call; 92, call; 93, identifier:self; 94, identifier:folders; 95, call; 96, identifier:f; 97, identifier:additional_fields; 98, block; 99, identifier:f; 100, identifier:additional_fields; 101, block; 102, identifier:calendar_view; 103, None; 104, call; 105, call; 106, identifier:q; 107, identifier:is_empty; 108, assignment; 109, assignment; 110, identifier:q; 111, identifier:query_string; 112, expression_statement; 113, expression_statement; 114, expression_statement; 115, expression_statement; 116, identifier:log; 117, identifier:debug; 118, string; 119, attribute; 120, attribute; 121, identifier:shape; 122, identifier:depth; 123, identifier:additional_fields; 124, conditional_expression:restriction.q if restriction else None; 125, attribute; 126, argument_list; 127, identifier:shape; 128, identifier:ID_ONLY; 129, identifier:additional_fields; 130, None; 131, identifier:i; 132, identifier:items; 133, block; 134, for_statement; 135, identifier:ValueError; 136, argument_list; 137, identifier:ValueError; 138, argument_list; 139, attribute; 140, argument_list; 141, expression_statement; 142, if_statement; 143, identifier:isinstance; 144, argument_list; 145, identifier:ValueError; 146, argument_list; 147, identifier:restriction; 148, None; 149, identifier:query_string; 150, None; 151, assignment; 152, assignment; 153, assignment; 154, assignment; 155, string_content:Finding %s items in folders %s (shape: %s, depth: %s, additional_fields: %s, restriction: %s); 156, identifier:self; 157, identifier:folders; 158, identifier:self; 159, identifier:account; 160, attribute; 161, identifier:restriction; 162, None; 163, call; 164, identifier:call; 165, keyword_argument; 166, keyword_argument; 167, keyword_argument; 168, keyword_argument; 169, keyword_argument; 170, keyword_argument; 171, keyword_argument; 172, keyword_argument; 173, keyword_argument; 174, expression_statement; 175, identifier:i; 176, identifier:items; 177, block; 178, binary_operator:"'shape' %s must be one of %s" % (shape, SHAPE_CHOICES); 179, binary_operator:"'depth' %s must be one of %s" % (depth, ITEM_TRAVERSAL_CHOICES); 180, identifier:log; 181, identifier:debug; 182, string; 183, call; 184, attribute; 185, block; 186, identifier:calendar_view; 187, identifier:CalendarView; 188, binary_operator:"'calendar_view' %s must be a CalendarView instance" % calendar_view; 189, identifier:restriction; 190, None; 191, identifier:query_string; 192, call; 193, identifier:restriction; 194, call; 195, identifier:query_string; 196, None; 197, identifier:restriction; 198, identifier:q; 199, identifier:FindItem; 200, argument_list; 201, identifier:additional_fields; 202, identifier:additional_fields; 203, identifier:restriction; 204, identifier:restriction; 205, identifier:order_fields; 206, identifier:order_fields; 207, identifier:shape; 208, identifier:shape; 209, identifier:query_string; 210, identifier:query_string; 211, identifier:depth; 212, identifier:depth; 213, identifier:calendar_view; 214, identifier:calendar_view; 215, identifier:max_items; 216, conditional_expression:calendar_view.max_items if calendar_view else max_items; 217, identifier:offset; 218, identifier:offset; 219, yield; 220, if_statement; 221, string:"'shape' %s must be one of %s"; 222, tuple; 223, string:"'depth' %s must be one of %s"; 224, tuple; 225, string_content:Folder list is empty; 226, attribute; 227, argument_list; 228, attribute; 229, identifier:is_complex; 230, raise_statement; 231, string:"'calendar_view' %s must be a CalendarView instance"; 232, identifier:calendar_view; 233, identifier:Restriction; 234, argument_list; 235, identifier:Restriction; 236, argument_list; 237, keyword_argument; 238, keyword_argument; 239, keyword_argument; 240, attribute; 241, identifier:calendar_view; 242, identifier:max_items; 243, conditional_expression:i if isinstance(i, Exception) else Item.id_from_xml(i); 244, call; 245, block; 246, else_clause; 247, identifier:shape; 248, identifier:SHAPE_CHOICES; 249, identifier:depth; 250, identifier:ITEM_TRAVERSAL_CHOICES; 251, identifier:self; 252, identifier:validate_item_field; 253, keyword_argument; 254, identifier:f; 255, identifier:field; 256, call; 257, identifier:q; 258, keyword_argument; 259, keyword_argument; 260, identifier:q; 261, keyword_argument; 262, keyword_argument; 263, identifier:account; 264, attribute; 265, identifier:folders; 266, attribute; 267, identifier:chunk_size; 268, identifier:page_size; 269, identifier:calendar_view; 270, identifier:max_items; 271, identifier:i; 272, call; 273, call; 274, identifier:isinstance; 275, argument_list; 276, expression_statement; 277, block; 278, identifier:field; 279, identifier:f; 280, identifier:ValueError; 281, argument_list; 282, identifier:folders; 283, attribute; 284, identifier:applies_to; 285, attribute; 286, identifier:folders; 287, attribute; 288, identifier:applies_to; 289, attribute; 290, identifier:self; 291, identifier:account; 292, identifier:self; 293, identifier:folders; 294, identifier:isinstance; 295, argument_list; 296, attribute; 297, argument_list; 298, identifier:i; 299, identifier:Exception; 300, yield; 301, expression_statement; 302, binary_operator:"find_items() does not support field '%s'. Use fetch() instead" % f.field.name; 303, identifier:self; 304, identifier:folders; 305, identifier:Restriction; 306, identifier:ITEMS; 307, identifier:self; 308, identifier:folders; 309, identifier:Restriction; 310, identifier:ITEMS; 311, identifier:i; 312, identifier:Exception; 313, identifier:Item; 314, identifier:id_from_xml; 315, identifier:i; 316, identifier:i; 317, yield; 318, string:"find_items() does not support field '%s'. Use fetch() instead"; 319, attribute; 320, call; 321, attribute; 322, identifier:name; 323, attribute; 324, argument_list; 325, identifier:f; 326, identifier:field; 327, call; 328, identifier:from_xml; 329, keyword_argument; 330, keyword_argument; 331, attribute; 332, argument_list; 333, identifier:elem; 334, identifier:i; 335, identifier:account; 336, attribute; 337, identifier:Folder; 338, identifier:item_model_from_tag; 339, attribute; 340, identifier:self; 341, identifier:account; 342, identifier:i; 343, identifier:tag | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 3, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 7, 26; 7, 27; 8, 28; 8, 29; 9, 30; 9, 31; 10, 32; 10, 33; 11, 34; 11, 35; 12, 36; 12, 37; 13, 38; 13, 39; 14, 40; 14, 41; 15, 42; 16, 43; 16, 44; 17, 45; 17, 46; 18, 47; 18, 48; 19, 49; 19, 50; 20, 51; 20, 52; 22, 53; 22, 54; 22, 55; 22, 56; 23, 57; 24, 58; 25, 59; 25, 60; 25, 61; 43, 62; 43, 63; 44, 64; 45, 65; 45, 66; 46, 67; 47, 68; 48, 69; 48, 70; 50, 71; 50, 72; 51, 73; 51, 74; 52, 75; 53, 76; 53, 77; 54, 78; 54, 79; 55, 80; 55, 81; 56, 82; 57, 83; 57, 84; 58, 85; 58, 86; 59, 87; 59, 88; 60, 89; 61, 90; 64, 91; 67, 92; 68, 93; 68, 94; 69, 95; 71, 96; 71, 97; 71, 98; 72, 99; 72, 100; 72, 101; 73, 102; 73, 103; 74, 104; 75, 105; 76, 106; 76, 107; 78, 108; 79, 109; 80, 110; 80, 111; 81, 112; 81, 113; 82, 114; 82, 115; 83, 116; 83, 117; 84, 118; 84, 119; 84, 120; 84, 121; 84, 122; 84, 123; 84, 124; 86, 125; 86, 126; 87, 127; 87, 128; 88, 129; 88, 130; 89, 131; 89, 132; 89, 133; 90, 134; 91, 135; 91, 136; 92, 137; 92, 138; 95, 139; 95, 140; 98, 141; 101, 142; 104, 143; 104, 144; 105, 145; 105, 146; 108, 147; 108, 148; 109, 149; 109, 150; 112, 151; 113, 152; 114, 153; 115, 154; 118, 155; 119, 156; 119, 157; 120, 158; 120, 159; 124, 160; 124, 161; 124, 162; 125, 163; 125, 164; 126, 165; 126, 166; 126, 167; 126, 168; 126, 169; 126, 170; 126, 171; 126, 172; 126, 173; 133, 174; 134, 175; 134, 176; 134, 177; 136, 178; 138, 179; 139, 180; 139, 181; 140, 182; 141, 183; 142, 184; 142, 185; 144, 186; 144, 187; 146, 188; 151, 189; 151, 190; 152, 191; 152, 192; 153, 193; 153, 194; 154, 195; 154, 196; 160, 197; 160, 198; 163, 199; 163, 200; 165, 201; 165, 202; 166, 203; 166, 204; 167, 205; 167, 206; 168, 207; 168, 208; 169, 209; 169, 210; 170, 211; 170, 212; 171, 213; 171, 214; 172, 215; 172, 216; 173, 217; 173, 218; 174, 219; 177, 220; 178, 221; 178, 222; 179, 223; 179, 224; 182, 225; 183, 226; 183, 227; 184, 228; 184, 229; 185, 230; 188, 231; 188, 232; 192, 233; 192, 234; 194, 235; 194, 236; 200, 237; 200, 238; 200, 239; 216, 240; 216, 241; 216, 242; 219, 243; 220, 244; 220, 245; 220, 246; 222, 247; 222, 248; 224, 249; 224, 250; 226, 251; 226, 252; 227, 253; 228, 254; 228, 255; 230, 256; 234, 257; 234, 258; 234, 259; 236, 260; 236, 261; 236, 262; 237, 263; 237, 264; 238, 265; 238, 266; 239, 267; 239, 268; 240, 269; 240, 270; 243, 271; 243, 272; 243, 273; 244, 274; 244, 275; 245, 276; 246, 277; 253, 278; 253, 279; 256, 280; 256, 281; 258, 282; 258, 283; 259, 284; 259, 285; 261, 286; 261, 287; 262, 288; 262, 289; 264, 290; 264, 291; 266, 292; 266, 293; 272, 294; 272, 295; 273, 296; 273, 297; 275, 298; 275, 299; 276, 300; 277, 301; 281, 302; 283, 303; 283, 304; 285, 305; 285, 306; 287, 307; 287, 308; 289, 309; 289, 310; 295, 311; 295, 312; 296, 313; 296, 314; 297, 315; 300, 316; 301, 317; 302, 318; 302, 319; 317, 320; 319, 321; 319, 322; 320, 323; 320, 324; 321, 325; 321, 326; 323, 327; 323, 328; 324, 329; 324, 330; 327, 331; 327, 332; 329, 333; 329, 334; 330, 335; 330, 336; 331, 337; 331, 338; 332, 339; 336, 340; 336, 341; 339, 342; 339, 343 | def find_items(self, q, shape=ID_ONLY, depth=SHALLOW, additional_fields=None, order_fields=None,
calendar_view=None, page_size=None, max_items=None, offset=0):
"""
Private method to call the FindItem service
:param q: a Q instance containing any restrictions
:param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is
non-null, we always return Item objects.
:param depth: controls the whether to return soft-deleted items or not.
:param additional_fields: the extra properties we want on the return objects. Default is no properties. Be
aware that complex fields can only be fetched with fetch() (i.e. the GetItem service).
:param order_fields: the SortOrder fields, if any
:param calendar_view: a CalendarView instance, if any
:param page_size: the requested number of items per page
:param max_items: the max number of items to return
:param offset: the offset relative to the first item in the item collection
:return: a generator for the returned item IDs or items
"""
if shape not in SHAPE_CHOICES:
raise ValueError("'shape' %s must be one of %s" % (shape, SHAPE_CHOICES))
if depth not in ITEM_TRAVERSAL_CHOICES:
raise ValueError("'depth' %s must be one of %s" % (depth, ITEM_TRAVERSAL_CHOICES))
if not self.folders:
log.debug('Folder list is empty')
return
if additional_fields:
for f in additional_fields:
self.validate_item_field(field=f)
for f in additional_fields:
if f.field.is_complex:
raise ValueError("find_items() does not support field '%s'. Use fetch() instead" % f.field.name)
if calendar_view is not None and not isinstance(calendar_view, CalendarView):
raise ValueError("'calendar_view' %s must be a CalendarView instance" % calendar_view)
# Build up any restrictions
if q.is_empty():
restriction = None
query_string = None
elif q.query_string:
restriction = None
query_string = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS)
else:
restriction = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS)
query_string = None
log.debug(
'Finding %s items in folders %s (shape: %s, depth: %s, additional_fields: %s, restriction: %s)',
self.folders,
self.account,
shape,
depth,
additional_fields,
restriction.q if restriction else None,
)
items = FindItem(account=self.account, folders=self.folders, chunk_size=page_size).call(
additional_fields=additional_fields,
restriction=restriction,
order_fields=order_fields,
shape=shape,
query_string=query_string,
depth=depth,
calendar_view=calendar_view,
max_items=calendar_view.max_items if calendar_view else max_items,
offset=offset,
)
if shape == ID_ONLY and additional_fields is None:
for i in items:
yield i if isinstance(i, Exception) else Item.id_from_xml(i)
else:
for i in items:
if isinstance(i, Exception):
yield i
else:
yield Folder.item_model_from_tag(i.tag).from_xml(elem=i, account=self.account) |
Subsets and Splits