nodes
stringlengths 501
22.4k
| edges
stringlengths 138
5.07k
| code
stringlengths 108
19.3k
|
---|---|---|
0, module; 1, function_definition; 2, function_name:_findRedundantProteins; 3, parameters; 4, block; 5, identifier:protToPeps; 6, identifier:pepToProts; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, comment:#TODO: quick and dirty solution; 15, comment:#NOTE: add a test for merged proteins; 16, expression_statement; 17, for_statement; 18, expression_statement; 19, for_statement; 20, expression_statement; 21, expression_statement; 22, for_statement; 23, return_statement; 24, identifier:proteins; 25, None; 26, comment:"""Returns a set of proteins with redundant peptide evidence.
After removing the redundant proteins from the "protToPeps" and "pepToProts"
mapping, all remaining proteins have at least one unique peptide. The
remaining proteins are a "minimal" set of proteins that are able to explain
all peptides. However, this is not guaranteed to be the optimal solution
with the least number of proteins. In addition it is possible that multiple
solutions with the same number of "minimal" proteins exist.
Procedure for finding the redundant proteins:
1. Generate a list of proteins that do not contain any unique peptides, a
unique peptide has exactly one protein entry in "pepToProts".
2. Proteins are first sorted in ascending order of the number of peptides.
Proteins with an equal number of peptides are sorted in descending order
of their sorted peptide frequencies (= proteins per peptide).
If two proteins are still equal, they are sorted alpha numerical in
descending order according to their protein names. For example in the
case of a tie between proteins "A" and "B", protein "B" would be
removed.
3. Parse this list of sorted non unique proteins;
If all its peptides have a frequency value of greater 1;
mark the protein as redundant; remove its peptides from the peptide
frequency count, continue with the next entry.
4. Return the set of proteins marked as redundant.
:param pepToProts: dict, for each peptide (=key) contains a set of parent
proteins (=value). For Example {peptide: {protein, ...}, ...}
:param protToPeps: dict, for each protein (=key) contains a set of
associated peptides (=value). For Example {protein: {peptide, ...}, ...}
:param proteins: iterable, proteins that are tested for being redundant. If
None all proteins in "protToPeps" are parsed.
:returns: a set of redundant proteins, i.e. proteins that are not necessary
to explain all peptides
"""; 27, comparison_operator:proteins is None; 28, block; 29, assignment; 30, assignment; 31, assignment; 32, assignment; 33, assignment; 34, identifier:protein; 35, identifier:proteins; 36, block; 37, assignment; 38, identifier:protein; 39, call; 40, block; 41, assignment; 42, assignment; 43, identifier:protein; 44, identifier:sortedProteins; 45, block; 46, identifier:redundantProteins; 47, identifier:proteins; 48, None; 49, expression_statement; 50, identifier:pepFrequency; 51, call; 52, identifier:protPepCounts; 53, call; 54, identifier:getCount; 55, call; 56, identifier:getProt; 57, call; 58, identifier:proteinTuples; 59, call; 60, if_statement; 61, identifier:sort; 62, call; 63, identifier:sorted; 64, argument_list; 65, if_statement; 66, expression_statement; 67, if_statement; 68, identifier:sortedProteins; 69, call; 70, identifier:redundantProteins; 71, call; 72, for_statement; 73, assignment; 74, identifier:_getValueCounts; 75, argument_list; 76, identifier:_getValueCounts; 77, argument_list; 78, attribute; 79, argument_list; 80, attribute; 81, argument_list; 82, identifier:list; 83, argument_list; 84, call; 85, block; 86, else_clause; 87, identifier:list; 88, argument_list; 89, identifier:proteinTuples; 90, keyword_argument; 91, comparison_operator:len(protein) == 1; 92, block; 93, assignment; 94, comparison_operator:min(protPepFreq) > 1; 95, block; 96, identifier:map; 97, argument_list; 98, identifier:set; 99, argument_list; 100, identifier:pep; 101, subscript; 102, block; 103, else_clause; 104, identifier:proteins; 105, call; 106, identifier:pepToProts; 107, identifier:protToPeps; 108, identifier:operator; 109, identifier:itemgetter; 110, integer:1; 111, identifier:operator; 112, identifier:itemgetter; 113, integer:0; 114, identifier:isinstance; 115, argument_list; 116, expression_statement; 117, block; 118, identifier:reverse; 119, True; 120, call; 121, integer:1; 122, expression_statement; 123, identifier:protPepFreq; 124, list_comprehension; 125, call; 126, integer:1; 127, expression_statement; 128, expression_statement; 129, identifier:getProt; 130, call; 131, identifier:protToPeps; 132, identifier:protein; 133, if_statement; 134, block; 135, identifier:viewkeys; 136, argument_list; 137, identifier:protein; 138, identifier:tuple; 139, call; 140, expression_statement; 141, identifier:len; 142, argument_list; 143, assignment; 144, subscript; 145, for_in_clause; 146, identifier:min; 147, argument_list; 148, assignment; 149, call; 150, identifier:sorted; 151, argument_list; 152, comparison_operator:pepFrequency[pep] <= 1; 153, block; 154, expression_statement; 155, expression_statement; 156, expression_statement; 157, identifier:protToPeps; 158, attribute; 159, argument_list; 160, call; 161, identifier:protein; 162, identifier:protein; 163, subscript; 164, identifier:pepFrequency; 165, identifier:pep; 166, identifier:pep; 167, subscript; 168, identifier:protPepFreq; 169, identifier:sortValue; 170, tuple; 171, attribute; 172, argument_list; 173, identifier:sort; 174, keyword_argument; 175, keyword_argument; 176, subscript; 177, integer:1; 178, break_statement; 179, assignment; 180, call; 181, call; 182, identifier:proteinTuples; 183, identifier:append; 184, identifier:protein; 185, attribute; 186, argument_list; 187, identifier:protein; 188, integer:0; 189, identifier:protToPeps; 190, identifier:protein; 191, binary_operator:len(protPepFreq)*-1; 192, call; 193, identifier:sort; 194, identifier:append; 195, tuple; 196, identifier:key; 197, identifier:getCount; 198, identifier:reverse; 199, True; 200, identifier:pepFrequency; 201, identifier:pep; 202, identifier:protPepFrequency; 203, call; 204, attribute; 205, argument_list; 206, attribute; 207, argument_list; 208, identifier:proteinTuples; 209, identifier:append; 210, call; 211, call; 212, unary_operator; 213, identifier:sorted; 214, argument_list; 215, identifier:protein; 216, identifier:sortValue; 217, identifier:Counter; 218, argument_list; 219, identifier:pepFrequency; 220, identifier:subtract; 221, identifier:protPepFrequency; 222, identifier:redundantProteins; 223, identifier:add; 224, identifier:protein; 225, identifier:tuple; 226, argument_list; 227, identifier:len; 228, argument_list; 229, integer:1; 230, identifier:protPepFreq; 231, keyword_argument; 232, subscript; 233, list; 234, identifier:protPepFreq; 235, identifier:reverse; 236, True; 237, identifier:protToPeps; 238, identifier:protein; 239, identifier:protein | 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; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 7, 24; 7, 25; 8, 26; 9, 27; 9, 28; 10, 29; 11, 30; 12, 31; 13, 32; 16, 33; 17, 34; 17, 35; 17, 36; 18, 37; 19, 38; 19, 39; 19, 40; 20, 41; 21, 42; 22, 43; 22, 44; 22, 45; 23, 46; 27, 47; 27, 48; 28, 49; 29, 50; 29, 51; 30, 52; 30, 53; 31, 54; 31, 55; 32, 56; 32, 57; 33, 58; 33, 59; 36, 60; 37, 61; 37, 62; 39, 63; 39, 64; 40, 65; 40, 66; 40, 67; 41, 68; 41, 69; 42, 70; 42, 71; 45, 72; 49, 73; 51, 74; 51, 75; 53, 76; 53, 77; 55, 78; 55, 79; 57, 80; 57, 81; 59, 82; 59, 83; 60, 84; 60, 85; 60, 86; 62, 87; 62, 88; 64, 89; 64, 90; 65, 91; 65, 92; 66, 93; 67, 94; 67, 95; 69, 96; 69, 97; 71, 98; 71, 99; 72, 100; 72, 101; 72, 102; 72, 103; 73, 104; 73, 105; 75, 106; 77, 107; 78, 108; 78, 109; 79, 110; 80, 111; 80, 112; 81, 113; 84, 114; 84, 115; 85, 116; 86, 117; 90, 118; 90, 119; 91, 120; 91, 121; 92, 122; 93, 123; 93, 124; 94, 125; 94, 126; 95, 127; 95, 128; 97, 129; 97, 130; 101, 131; 101, 132; 102, 133; 103, 134; 105, 135; 105, 136; 115, 137; 115, 138; 116, 139; 117, 140; 120, 141; 120, 142; 122, 143; 124, 144; 124, 145; 125, 146; 125, 147; 127, 148; 128, 149; 130, 150; 130, 151; 133, 152; 133, 153; 134, 154; 134, 155; 134, 156; 136, 157; 139, 158; 139, 159; 140, 160; 142, 161; 143, 162; 143, 163; 144, 164; 144, 165; 145, 166; 145, 167; 147, 168; 148, 169; 148, 170; 149, 171; 149, 172; 151, 173; 151, 174; 151, 175; 152, 176; 152, 177; 153, 178; 154, 179; 155, 180; 156, 181; 158, 182; 158, 183; 159, 184; 160, 185; 160, 186; 163, 187; 163, 188; 167, 189; 167, 190; 170, 191; 170, 192; 171, 193; 171, 194; 172, 195; 174, 196; 174, 197; 175, 198; 175, 199; 176, 200; 176, 201; 179, 202; 179, 203; 180, 204; 180, 205; 181, 206; 181, 207; 185, 208; 185, 209; 186, 210; 191, 211; 191, 212; 192, 213; 192, 214; 195, 215; 195, 216; 203, 217; 203, 218; 204, 219; 204, 220; 205, 221; 206, 222; 206, 223; 207, 224; 210, 225; 210, 226; 211, 227; 211, 228; 212, 229; 214, 230; 214, 231; 218, 232; 226, 233; 228, 234; 231, 235; 231, 236; 232, 237; 232, 238; 233, 239 | def _findRedundantProteins(protToPeps, pepToProts, proteins=None):
"""Returns a set of proteins with redundant peptide evidence.
After removing the redundant proteins from the "protToPeps" and "pepToProts"
mapping, all remaining proteins have at least one unique peptide. The
remaining proteins are a "minimal" set of proteins that are able to explain
all peptides. However, this is not guaranteed to be the optimal solution
with the least number of proteins. In addition it is possible that multiple
solutions with the same number of "minimal" proteins exist.
Procedure for finding the redundant proteins:
1. Generate a list of proteins that do not contain any unique peptides, a
unique peptide has exactly one protein entry in "pepToProts".
2. Proteins are first sorted in ascending order of the number of peptides.
Proteins with an equal number of peptides are sorted in descending order
of their sorted peptide frequencies (= proteins per peptide).
If two proteins are still equal, they are sorted alpha numerical in
descending order according to their protein names. For example in the
case of a tie between proteins "A" and "B", protein "B" would be
removed.
3. Parse this list of sorted non unique proteins;
If all its peptides have a frequency value of greater 1;
mark the protein as redundant; remove its peptides from the peptide
frequency count, continue with the next entry.
4. Return the set of proteins marked as redundant.
:param pepToProts: dict, for each peptide (=key) contains a set of parent
proteins (=value). For Example {peptide: {protein, ...}, ...}
:param protToPeps: dict, for each protein (=key) contains a set of
associated peptides (=value). For Example {protein: {peptide, ...}, ...}
:param proteins: iterable, proteins that are tested for being redundant. If
None all proteins in "protToPeps" are parsed.
:returns: a set of redundant proteins, i.e. proteins that are not necessary
to explain all peptides
"""
if proteins is None:
proteins = viewkeys(protToPeps)
pepFrequency = _getValueCounts(pepToProts)
protPepCounts = _getValueCounts(protToPeps)
getCount = operator.itemgetter(1)
getProt = operator.itemgetter(0)
#TODO: quick and dirty solution
#NOTE: add a test for merged proteins
proteinTuples = list()
for protein in proteins:
if isinstance(protein, tuple):
proteinTuples.append(protein)
else:
proteinTuples.append(tuple([protein]))
sort = list()
for protein in sorted(proteinTuples, reverse=True):
if len(protein) == 1:
protein = protein[0]
protPepFreq = [pepFrequency[pep] for pep in protToPeps[protein]]
if min(protPepFreq) > 1:
sortValue = (len(protPepFreq)*-1, sorted(protPepFreq, reverse=True))
sort.append((protein, sortValue))
sortedProteins = map(getProt, sorted(sort, key=getCount, reverse=True))
redundantProteins = set()
for protein in sortedProteins:
for pep in protToPeps[protein]:
if pepFrequency[pep] <= 1:
break
else:
protPepFrequency = Counter(protToPeps[protein])
pepFrequency.subtract(protPepFrequency)
redundantProteins.add(protein)
return redundantProteins |
0, module; 1, function_definition; 2, function_name:_mergeProteinEntries; 3, parameters; 4, block; 5, identifier:proteinLists; 6, identifier:protToPeps; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""Returns a new "protToPeps" dictionary with entries merged that are
present in proteinLists.
NOTE:
The key of the merged entry is a tuple of the sorted protein keys. This
behaviour might change in the future; the tuple might be replaced by
simply one of the protein entries which is then representative for all.
:param proteinLists: a list of protein groups that will be merged
[{protein, ...}, ...]
:param protToPeps: dict, for each protein (=key) contains a set of
associated peptides (=value). For Example {protein: {peptide, ...}, ...}
:returns: dict, {protein: set([peptid, ...])}
"""; 12, assignment; 13, identifier:proteins; 14, identifier:proteinLists; 15, block; 16, identifier:mergedProtToPeps; 17, identifier:mergedProtToPeps; 18, call; 19, for_statement; 20, expression_statement; 21, expression_statement; 22, identifier:dict; 23, argument_list; 24, identifier:protein; 25, identifier:proteins; 26, block; 27, assignment; 28, assignment; 29, identifier:protToPeps; 30, expression_statement; 31, identifier:mergedProtein; 32, call; 33, subscript; 34, identifier:peptides; 35, assignment; 36, identifier:tuple; 37, argument_list; 38, identifier:mergedProtToPeps; 39, identifier:mergedProtein; 40, identifier:peptides; 41, call; 42, call; 43, attribute; 44, argument_list; 45, identifier:sorted; 46, argument_list; 47, identifier:mergedProtToPeps; 48, identifier:pop; 49, identifier:protein; 50, identifier:proteins | 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; 15, 19; 15, 20; 15, 21; 18, 22; 18, 23; 19, 24; 19, 25; 19, 26; 20, 27; 21, 28; 23, 29; 26, 30; 27, 31; 27, 32; 28, 33; 28, 34; 30, 35; 32, 36; 32, 37; 33, 38; 33, 39; 35, 40; 35, 41; 37, 42; 41, 43; 41, 44; 42, 45; 42, 46; 43, 47; 43, 48; 44, 49; 46, 50 | def _mergeProteinEntries(proteinLists, protToPeps):
"""Returns a new "protToPeps" dictionary with entries merged that are
present in proteinLists.
NOTE:
The key of the merged entry is a tuple of the sorted protein keys. This
behaviour might change in the future; the tuple might be replaced by
simply one of the protein entries which is then representative for all.
:param proteinLists: a list of protein groups that will be merged
[{protein, ...}, ...]
:param protToPeps: dict, for each protein (=key) contains a set of
associated peptides (=value). For Example {protein: {peptide, ...}, ...}
:returns: dict, {protein: set([peptid, ...])}
"""
mergedProtToPeps = dict(protToPeps)
for proteins in proteinLists:
for protein in proteins:
peptides = mergedProtToPeps.pop(protein)
mergedProtein = tuple(sorted(proteins))
mergedProtToPeps[mergedProtein] = peptides
return mergedProtToPeps |
0, module; 1, function_definition; 2, function_name:_list; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, function_definition; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, return_statement; 16, identifier:foldername; 17, string:"INBOX"; 18, identifier:reverse; 19, False; 20, identifier:since; 21, None; 22, comment:"""Do structured list output.
Sorts the list by date, possibly reversed, filtered from 'since'.
The returned list is: foldername, message key, message object
"""; 23, assignment; 24, function_name:sortcmp; 25, parameters; 26, block; 27, assignment; 28, assignment; 29, assignment; 30, identifier:itemlist; 31, identifier:folder; 32, conditional_expression:self.folder \
if foldername == "INBOX" \
else self._getfolder(foldername); 33, identifier:d; 34, try_statement; 35, identifier:lst; 36, conditional_expression:folder.items() if not since else folder.items_since(since); 37, identifier:sorted_lst; 38, call; 39, identifier:itemlist; 40, list_comprehension; 41, attribute; 42, line_continuation:\; 43, comparison_operator:foldername == "INBOX"; 44, line_continuation:\; 45, call; 46, block; 47, except_clause; 48, call; 49, not_operator; 50, call; 51, identifier:sorted; 52, argument_list; 53, tuple; 54, for_in_clause; 55, identifier:self; 56, identifier:folder; 57, identifier:foldername; 58, string:"INBOX"; 59, attribute; 60, argument_list; 61, return_statement; 62, block; 63, attribute; 64, argument_list; 65, identifier:since; 66, attribute; 67, argument_list; 68, identifier:lst; 69, keyword_argument; 70, keyword_argument; 71, identifier:folder; 72, identifier:key; 73, identifier:msg; 74, pattern_list; 75, identifier:sorted_lst; 76, identifier:self; 77, identifier:_getfolder; 78, identifier:foldername; 79, attribute; 80, return_statement; 81, identifier:folder; 82, identifier:items; 83, identifier:folder; 84, identifier:items_since; 85, identifier:since; 86, identifier:key; 87, identifier:sortcmp; 88, identifier:reverse; 89, conditional_expression:1 if reverse else 0; 90, identifier:key; 91, identifier:msg; 92, subscript; 93, identifier:date; 94, unary_operator; 95, integer:1; 96, identifier:reverse; 97, integer:0; 98, identifier:d; 99, integer:1; 100, 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; 6, 16; 6, 17; 7, 18; 7, 19; 8, 20; 8, 21; 9, 22; 10, 23; 11, 24; 11, 25; 11, 26; 12, 27; 13, 28; 14, 29; 15, 30; 23, 31; 23, 32; 25, 33; 26, 34; 27, 35; 27, 36; 28, 37; 28, 38; 29, 39; 29, 40; 32, 41; 32, 42; 32, 43; 32, 44; 32, 45; 34, 46; 34, 47; 36, 48; 36, 49; 36, 50; 38, 51; 38, 52; 40, 53; 40, 54; 41, 55; 41, 56; 43, 57; 43, 58; 45, 59; 45, 60; 46, 61; 47, 62; 48, 63; 48, 64; 49, 65; 50, 66; 50, 67; 52, 68; 52, 69; 52, 70; 53, 71; 53, 72; 53, 73; 54, 74; 54, 75; 59, 76; 59, 77; 60, 78; 61, 79; 62, 80; 63, 81; 63, 82; 66, 83; 66, 84; 67, 85; 69, 86; 69, 87; 70, 88; 70, 89; 74, 90; 74, 91; 79, 92; 79, 93; 80, 94; 89, 95; 89, 96; 89, 97; 92, 98; 92, 99; 94, 100 | def _list(self, foldername="INBOX", reverse=False, since=None):
"""Do structured list output.
Sorts the list by date, possibly reversed, filtered from 'since'.
The returned list is: foldername, message key, message object
"""
folder = self.folder \
if foldername == "INBOX" \
else self._getfolder(foldername)
def sortcmp(d):
try:
return d[1].date
except:
return -1
lst = folder.items() if not since else folder.items_since(since)
sorted_lst = sorted(lst, key=sortcmp, reverse=1 if reverse else 0)
itemlist = [(folder, key, msg) for key,msg in sorted_lst]
return itemlist |
0, module; 1, function_definition; 2, function_name:sort_entries; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, return_statement; 8, comment:"""Get whether reverse is True or False. Return the sorted data."""; 9, call; 10, identifier:sorted; 11, argument_list; 12, attribute; 13, keyword_argument; 14, keyword_argument; 15, identifier:self; 16, identifier:data; 17, identifier:key; 18, attribute; 19, identifier:reverse; 20, call; 21, identifier:self; 22, identifier:sort_func; 23, attribute; 24, argument_list; 25, identifier:self; 26, identifier:get_reverse | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 9, 10; 9, 11; 11, 12; 11, 13; 11, 14; 12, 15; 12, 16; 13, 17; 13, 18; 14, 19; 14, 20; 18, 21; 18, 22; 20, 23; 20, 24; 23, 25; 23, 26 | def sort_entries(self):
"""Get whether reverse is True or False. Return the sorted data."""
return sorted(self.data, key=self.sort_func, reverse=self.get_reverse()) |
0, module; 1, function_definition; 2, function_name:expectedLabelPosition; 3, parameters; 4, block; 5, identifier:peptide; 6, identifier:labelStateInfo; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, if_statement; 11, if_statement; 12, expression_statement; 13, for_statement; 14, if_statement; 15, for_statement; 16, return_statement; 17, identifier:sequence; 18, None; 19, identifier:modPositions; 20, None; 21, comment:"""Returns a modification description of a certain label state of a peptide.
:param peptide: Peptide sequence used to calculat the expected label state
modifications
:param labelStateInfo: An entry of :attr:`LabelDescriptor.labels` that
describes a label state
:param sequence: unmodified amino acid sequence of :var:`peptide`, if None
it is generated by :func:`maspy.peptidemethods.removeModifications()`
:param modPositions: dictionary describing the modification state of
"peptide", if None it is generated by
:func:`maspy.peptidemethods.returnModPositions()`
:returns: {sequence position: sorted list of expected label modifications
on that position, ...
}
"""; 22, comparison_operator:modPositions is None; 23, block; 24, comparison_operator:sequence is None; 25, block; 26, assignment; 27, pattern_list; 28, call; 29, block; 30, comparison_operator:labelStateInfo['excludingModifications'] is not None; 31, block; 32, identifier:sequencePosition; 33, call; 34, block; 35, identifier:currLabelMods; 36, identifier:modPositions; 37, None; 38, expression_statement; 39, identifier:sequence; 40, None; 41, expression_statement; 42, identifier:currLabelMods; 43, call; 44, identifier:labelPosition; 45, identifier:labelSymbols; 46, identifier:viewitems; 47, argument_list; 48, expression_statement; 49, if_statement; 50, subscript; 51, None; 52, for_statement; 53, identifier:list; 54, argument_list; 55, expression_statement; 56, assignment; 57, assignment; 58, identifier:dict; 59, argument_list; 60, subscript; 61, assignment; 62, comparison_operator:labelSymbols == ['']; 63, block; 64, elif_clause; 65, else_clause; 66, identifier:labelStateInfo; 67, string; 68, pattern_list; 69, call; 70, block; 71, call; 72, assignment; 73, identifier:modPositions; 74, call; 75, identifier:sequence; 76, call; 77, identifier:labelStateInfo; 78, string; 79, identifier:labelSymbols; 80, call; 81, identifier:labelSymbols; 82, list; 83, pass_statement; 84, comparison_operator:labelPosition == 'nTerm'; 85, block; 86, block; 87, string_content:excludingModifications; 88, identifier:excludingMod; 89, identifier:excludedLabelSymbol; 90, identifier:viewitems; 91, argument_list; 92, if_statement; 93, for_statement; 94, identifier:viewkeys; 95, argument_list; 96, subscript; 97, call; 98, attribute; 99, argument_list; 100, attribute; 101, argument_list; 102, string_content:aminoAcidLabels; 103, attribute; 104, argument_list; 105, string; 106, identifier:labelPosition; 107, string; 108, expression_statement; 109, expression_statement; 110, for_statement; 111, subscript; 112, comparison_operator:excludingMod not in modPositions; 113, block; 114, identifier:excludingModPos; 115, subscript; 116, block; 117, identifier:currLabelMods; 118, identifier:currLabelMods; 119, identifier:sequencePosition; 120, identifier:sorted; 121, argument_list; 122, attribute; 123, identifier:returnModPositions; 124, identifier:peptide; 125, keyword_argument; 126, attribute; 127, identifier:removeModifications; 128, identifier:peptide; 129, identifier:aux; 130, identifier:toList; 131, identifier:labelSymbols; 132, string_content:nTerm; 133, call; 134, call; 135, identifier:sequencePosition; 136, call; 137, block; 138, identifier:labelStateInfo; 139, string; 140, identifier:excludingMod; 141, identifier:modPositions; 142, continue_statement; 143, identifier:modPositions; 144, identifier:excludingMod; 145, if_statement; 146, if_statement; 147, if_statement; 148, subscript; 149, identifier:maspy; 150, identifier:peptidemethods; 151, identifier:indexStart; 152, integer:0; 153, identifier:maspy; 154, identifier:peptidemethods; 155, attribute; 156, argument_list; 157, attribute; 158, argument_list; 159, attribute; 160, argument_list; 161, expression_statement; 162, expression_statement; 163, string_content:excludingModifications; 164, comparison_operator:excludingModPos not in currLabelMods; 165, block; 166, comparison_operator:excludedLabelSymbol not in currLabelMods[excludingModPos]; 167, block; 168, comparison_operator:len(currLabelMods[excludingModPos]) == 1; 169, block; 170, else_clause; 171, identifier:currLabelMods; 172, identifier:sequencePosition; 173, identifier:currLabelMods; 174, identifier:setdefault; 175, integer:0; 176, call; 177, subscript; 178, identifier:extend; 179, identifier:labelSymbols; 180, identifier:aux; 181, identifier:findAllSubstrings; 182, identifier:sequence; 183, identifier:labelPosition; 184, call; 185, call; 186, identifier:excludingModPos; 187, identifier:currLabelMods; 188, continue_statement; 189, identifier:excludedLabelSymbol; 190, subscript; 191, continue_statement; 192, call; 193, integer:1; 194, delete_statement; 195, block; 196, identifier:list; 197, argument_list; 198, identifier:currLabelMods; 199, integer:0; 200, attribute; 201, argument_list; 202, attribute; 203, argument_list; 204, identifier:currLabelMods; 205, identifier:excludingModPos; 206, identifier:len; 207, argument_list; 208, parenthesized_expression; 209, expression_statement; 210, expression_statement; 211, identifier:currLabelMods; 212, identifier:setdefault; 213, identifier:sequencePosition; 214, call; 215, subscript; 216, identifier:extend; 217, identifier:labelSymbols; 218, subscript; 219, subscript; 220, assignment; 221, call; 222, identifier:list; 223, argument_list; 224, identifier:currLabelMods; 225, identifier:sequencePosition; 226, identifier:currLabelMods; 227, identifier:excludingModPos; 228, identifier:currLabelMods; 229, identifier:excludingModPos; 230, identifier:excludedModIndex; 231, call; 232, attribute; 233, argument_list; 234, attribute; 235, argument_list; 236, subscript; 237, identifier:pop; 238, identifier:excludedModIndex; 239, subscript; 240, identifier:index; 241, identifier:excludedLabelSymbol; 242, identifier:currLabelMods; 243, identifier:excludingModPos; 244, identifier:currLabelMods; 245, identifier:excludingModPos | 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; 7, 17; 7, 18; 8, 19; 8, 20; 9, 21; 10, 22; 10, 23; 11, 24; 11, 25; 12, 26; 13, 27; 13, 28; 13, 29; 14, 30; 14, 31; 15, 32; 15, 33; 15, 34; 16, 35; 22, 36; 22, 37; 23, 38; 24, 39; 24, 40; 25, 41; 26, 42; 26, 43; 27, 44; 27, 45; 28, 46; 28, 47; 29, 48; 29, 49; 30, 50; 30, 51; 31, 52; 33, 53; 33, 54; 34, 55; 38, 56; 41, 57; 43, 58; 43, 59; 47, 60; 48, 61; 49, 62; 49, 63; 49, 64; 49, 65; 50, 66; 50, 67; 52, 68; 52, 69; 52, 70; 54, 71; 55, 72; 56, 73; 56, 74; 57, 75; 57, 76; 60, 77; 60, 78; 61, 79; 61, 80; 62, 81; 62, 82; 63, 83; 64, 84; 64, 85; 65, 86; 67, 87; 68, 88; 68, 89; 69, 90; 69, 91; 70, 92; 70, 93; 71, 94; 71, 95; 72, 96; 72, 97; 74, 98; 74, 99; 76, 100; 76, 101; 78, 102; 80, 103; 80, 104; 82, 105; 84, 106; 84, 107; 85, 108; 85, 109; 86, 110; 91, 111; 92, 112; 92, 113; 93, 114; 93, 115; 93, 116; 95, 117; 96, 118; 96, 119; 97, 120; 97, 121; 98, 122; 98, 123; 99, 124; 99, 125; 100, 126; 100, 127; 101, 128; 103, 129; 103, 130; 104, 131; 107, 132; 108, 133; 109, 134; 110, 135; 110, 136; 110, 137; 111, 138; 111, 139; 112, 140; 112, 141; 113, 142; 115, 143; 115, 144; 116, 145; 116, 146; 116, 147; 121, 148; 122, 149; 122, 150; 125, 151; 125, 152; 126, 153; 126, 154; 133, 155; 133, 156; 134, 157; 134, 158; 136, 159; 136, 160; 137, 161; 137, 162; 139, 163; 145, 164; 145, 165; 146, 166; 146, 167; 147, 168; 147, 169; 147, 170; 148, 171; 148, 172; 155, 173; 155, 174; 156, 175; 156, 176; 157, 177; 157, 178; 158, 179; 159, 180; 159, 181; 160, 182; 160, 183; 161, 184; 162, 185; 164, 186; 164, 187; 165, 188; 166, 189; 166, 190; 167, 191; 168, 192; 168, 193; 169, 194; 170, 195; 176, 196; 176, 197; 177, 198; 177, 199; 184, 200; 184, 201; 185, 202; 185, 203; 190, 204; 190, 205; 192, 206; 192, 207; 194, 208; 195, 209; 195, 210; 200, 211; 200, 212; 201, 213; 201, 214; 202, 215; 202, 216; 203, 217; 207, 218; 208, 219; 209, 220; 210, 221; 214, 222; 214, 223; 215, 224; 215, 225; 218, 226; 218, 227; 219, 228; 219, 229; 220, 230; 220, 231; 221, 232; 221, 233; 231, 234; 231, 235; 232, 236; 232, 237; 233, 238; 234, 239; 234, 240; 235, 241; 236, 242; 236, 243; 239, 244; 239, 245 | def expectedLabelPosition(peptide, labelStateInfo, sequence=None,
modPositions=None):
"""Returns a modification description of a certain label state of a peptide.
:param peptide: Peptide sequence used to calculat the expected label state
modifications
:param labelStateInfo: An entry of :attr:`LabelDescriptor.labels` that
describes a label state
:param sequence: unmodified amino acid sequence of :var:`peptide`, if None
it is generated by :func:`maspy.peptidemethods.removeModifications()`
:param modPositions: dictionary describing the modification state of
"peptide", if None it is generated by
:func:`maspy.peptidemethods.returnModPositions()`
:returns: {sequence position: sorted list of expected label modifications
on that position, ...
}
"""
if modPositions is None:
modPositions = maspy.peptidemethods.returnModPositions(peptide,
indexStart=0
)
if sequence is None:
sequence = maspy.peptidemethods.removeModifications(peptide)
currLabelMods = dict()
for labelPosition, labelSymbols in viewitems(labelStateInfo['aminoAcidLabels']):
labelSymbols = aux.toList(labelSymbols)
if labelSymbols == ['']:
pass
elif labelPosition == 'nTerm':
currLabelMods.setdefault(0, list())
currLabelMods[0].extend(labelSymbols)
else:
for sequencePosition in aux.findAllSubstrings(sequence,
labelPosition):
currLabelMods.setdefault(sequencePosition, list())
currLabelMods[sequencePosition].extend(labelSymbols)
if labelStateInfo['excludingModifications'] is not None:
for excludingMod, excludedLabelSymbol in viewitems(labelStateInfo['excludingModifications']):
if excludingMod not in modPositions:
continue
for excludingModPos in modPositions[excludingMod]:
if excludingModPos not in currLabelMods:
continue
if excludedLabelSymbol not in currLabelMods[excludingModPos]:
continue
if len(currLabelMods[excludingModPos]) == 1:
del(currLabelMods[excludingModPos])
else:
excludedModIndex = currLabelMods[excludingModPos].index(excludedLabelSymbol)
currLabelMods[excludingModPos].pop(excludedModIndex)
for sequencePosition in list(viewkeys(currLabelMods)):
currLabelMods[sequencePosition] = sorted(currLabelMods[sequencePosition])
return currLabelMods |
0, module; 1, function_definition; 2, function_name:rank; 3, parameters; 4, block; 5, identifier:self; 6, identifier:member; 7, expression_statement; 8, if_statement; 9, return_statement; 10, comment:""" Gets the ASC rank of @member from the sorted set, that is,
lower scores have lower ranks
"""; 11, attribute; 12, block; 13, call; 14, identifier:self; 15, identifier:reversed; 16, return_statement; 17, attribute; 18, argument_list; 19, call; 20, attribute; 21, identifier:zrank; 22, attribute; 23, call; 24, attribute; 25, argument_list; 26, identifier:self; 27, identifier:_client; 28, identifier:self; 29, identifier:key_prefix; 30, attribute; 31, argument_list; 32, attribute; 33, identifier:zrevrank; 34, attribute; 35, call; 36, identifier:self; 37, identifier:_dumps; 38, identifier:member; 39, identifier:self; 40, identifier:_client; 41, identifier:self; 42, identifier:key_prefix; 43, attribute; 44, argument_list; 45, identifier:self; 46, identifier:_dumps; 47, identifier:member | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 8, 12; 9, 13; 11, 14; 11, 15; 12, 16; 13, 17; 13, 18; 16, 19; 17, 20; 17, 21; 18, 22; 18, 23; 19, 24; 19, 25; 20, 26; 20, 27; 22, 28; 22, 29; 23, 30; 23, 31; 24, 32; 24, 33; 25, 34; 25, 35; 30, 36; 30, 37; 31, 38; 32, 39; 32, 40; 34, 41; 34, 42; 35, 43; 35, 44; 43, 45; 43, 46; 44, 47 | def rank(self, member):
""" Gets the ASC rank of @member from the sorted set, that is,
lower scores have lower ranks
"""
if self.reversed:
return self._client.zrevrank(self.key_prefix, self._dumps(member))
return self._client.zrank(self.key_prefix, self._dumps(member)) |
0, module; 1, function_definition; 2, function_name:prepareSiiImport; 3, parameters; 4, block; 5, identifier:siiContainer; 6, identifier:specfile; 7, identifier:path; 8, identifier:qcAttr; 9, identifier:qcLargerBetter; 10, identifier:qcCutoff; 11, identifier:rankAttr; 12, identifier:rankLargerBetter; 13, expression_statement; 14, if_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, comment:"""Prepares the ``siiContainer`` for the import of peptide spectrum matching
results. Adds entries to ``siiContainer.container`` and to
``siiContainer.info``.
:param siiContainer: instance of :class:`maspy.core.SiiContainer`
:param specfile: unambiguous identifier of a ms-run file. Is also used as
a reference to other MasPy file containers.
:param path: folder location used by the ``SiiContainer`` to save and load
data to the hard disk.
:param qcAttr: name of the parameter to define a ``Sii`` quality cut off.
Typically this is some sort of a global false positive estimator,
for example a 'false discovery rate' (FDR).
:param qcLargerBetter: bool, True if a large value for the ``.qcAttr`` means
a higher confidence.
:param qcCutOff: float, the quality threshold for the specifed ``.qcAttr``
:param rankAttr: name of the parameter used for ranking ``Sii`` according
to how well they match to a fragment ion spectrum, in the case when
their are multiple ``Sii`` present for the same spectrum.
:param rankLargerBetter: bool, True if a large value for the ``.rankAttr``
means a better match to the fragment ion spectrum.
For details on ``Sii`` ranking see :func:`applySiiRanking()`
For details on ``Sii`` quality validation see :func:`applySiiQcValidation()`
"""; 21, comparison_operator:specfile not in siiContainer.info; 22, block; 23, else_clause; 24, assignment; 25, assignment; 26, assignment; 27, assignment; 28, assignment; 29, identifier:specfile; 30, attribute; 31, expression_statement; 32, block; 33, subscript; 34, identifier:qcAttr; 35, subscript; 36, identifier:qcLargerBetter; 37, subscript; 38, identifier:qcCutoff; 39, subscript; 40, identifier:rankAttr; 41, subscript; 42, identifier:rankLargerBetter; 43, identifier:siiContainer; 44, identifier:info; 45, call; 46, raise_statement; 47, subscript; 48, string; 49, subscript; 50, string; 51, subscript; 52, string; 53, subscript; 54, string; 55, subscript; 56, string; 57, attribute; 58, argument_list; 59, call; 60, attribute; 61, identifier:specfile; 62, string_content:qcAttr; 63, attribute; 64, identifier:specfile; 65, string_content:qcLargerBetter; 66, attribute; 67, identifier:specfile; 68, string_content:qcCutoff; 69, attribute; 70, identifier:specfile; 71, string_content:rankAttr; 72, attribute; 73, identifier:specfile; 74, string_content:rankLargerBetter; 75, identifier:siiContainer; 76, identifier:addSpecfile; 77, identifier:specfile; 78, identifier:path; 79, identifier:Exception; 80, argument_list; 81, identifier:siiContainer; 82, identifier:info; 83, identifier:siiContainer; 84, identifier:info; 85, identifier:siiContainer; 86, identifier:info; 87, identifier:siiContainer; 88, identifier:info; 89, identifier:siiContainer; 90, identifier:info; 91, string; 92, string_content:... | 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; 13, 20; 14, 21; 14, 22; 14, 23; 15, 24; 16, 25; 17, 26; 18, 27; 19, 28; 21, 29; 21, 30; 22, 31; 23, 32; 24, 33; 24, 34; 25, 35; 25, 36; 26, 37; 26, 38; 27, 39; 27, 40; 28, 41; 28, 42; 30, 43; 30, 44; 31, 45; 32, 46; 33, 47; 33, 48; 35, 49; 35, 50; 37, 51; 37, 52; 39, 53; 39, 54; 41, 55; 41, 56; 45, 57; 45, 58; 46, 59; 47, 60; 47, 61; 48, 62; 49, 63; 49, 64; 50, 65; 51, 66; 51, 67; 52, 68; 53, 69; 53, 70; 54, 71; 55, 72; 55, 73; 56, 74; 57, 75; 57, 76; 58, 77; 58, 78; 59, 79; 59, 80; 60, 81; 60, 82; 63, 83; 63, 84; 66, 85; 66, 86; 69, 87; 69, 88; 72, 89; 72, 90; 80, 91; 91, 92 | def prepareSiiImport(siiContainer, specfile, path, qcAttr, qcLargerBetter,
qcCutoff, rankAttr, rankLargerBetter):
"""Prepares the ``siiContainer`` for the import of peptide spectrum matching
results. Adds entries to ``siiContainer.container`` and to
``siiContainer.info``.
:param siiContainer: instance of :class:`maspy.core.SiiContainer`
:param specfile: unambiguous identifier of a ms-run file. Is also used as
a reference to other MasPy file containers.
:param path: folder location used by the ``SiiContainer`` to save and load
data to the hard disk.
:param qcAttr: name of the parameter to define a ``Sii`` quality cut off.
Typically this is some sort of a global false positive estimator,
for example a 'false discovery rate' (FDR).
:param qcLargerBetter: bool, True if a large value for the ``.qcAttr`` means
a higher confidence.
:param qcCutOff: float, the quality threshold for the specifed ``.qcAttr``
:param rankAttr: name of the parameter used for ranking ``Sii`` according
to how well they match to a fragment ion spectrum, in the case when
their are multiple ``Sii`` present for the same spectrum.
:param rankLargerBetter: bool, True if a large value for the ``.rankAttr``
means a better match to the fragment ion spectrum.
For details on ``Sii`` ranking see :func:`applySiiRanking()`
For details on ``Sii`` quality validation see :func:`applySiiQcValidation()`
"""
if specfile not in siiContainer.info:
siiContainer.addSpecfile(specfile, path)
else:
raise Exception('...')
siiContainer.info[specfile]['qcAttr'] = qcAttr
siiContainer.info[specfile]['qcLargerBetter'] = qcLargerBetter
siiContainer.info[specfile]['qcCutoff'] = qcCutoff
siiContainer.info[specfile]['rankAttr'] = rankAttr
siiContainer.info[specfile]['rankLargerBetter'] = rankLargerBetter |
0, module; 1, function_definition; 2, function_name:find_nearest; 3, parameters; 4, type; 5, block; 6, identifier:x; 7, identifier:x0; 8, generic_type; 9, expression_statement; 10, expression_statement; 11, comment:# for indexing upon return; 12, expression_statement; 13, comment:# %%; 14, if_statement; 15, if_statement; 16, comment:# %%; 17, expression_statement; 18, comment:# NOTE: not trapping IndexError (all-nan) becaues returning None can surprise with slice indexing; 19, for_statement; 20, return_statement; 21, identifier:Tuple; 22, type_parameter; 23, comment:"""
This find_nearest function does NOT assume sorted input
inputs:
x: array (float, int, datetime, h5py.Dataset) within which to search for x0
x0: singleton or array of values to search for in x
outputs:
idx: index of flattened x nearest to x0 (i.e. works with higher than 1-D arrays also)
xidx: x[idx]
Observe how bisect.bisect() gives the incorrect result!
idea based on:
http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array
"""; 24, assignment; 25, assignment; 26, boolean_operator; 27, block; 28, comparison_operator:x0.ndim not in (0, 1); 29, block; 30, assignment; 31, pattern_list; 32, call; 33, block; 34, expression_list; 35, type; 36, type; 37, identifier:x; 38, call; 39, identifier:x0; 40, call; 41, comparison_operator:x.size == 0; 42, comparison_operator:x0.size == 0; 43, raise_statement; 44, attribute; 45, tuple; 46, raise_statement; 47, identifier:ind; 48, call; 49, identifier:i; 50, identifier:xi; 51, identifier:enumerate; 52, argument_list; 53, if_statement; 54, subscript; 55, subscript; 56, identifier:int; 57, identifier:Any; 58, attribute; 59, argument_list; 60, attribute; 61, argument_list; 62, attribute; 63, integer:0; 64, attribute; 65, integer:0; 66, call; 67, identifier:x0; 68, identifier:ndim; 69, integer:0; 70, integer:1; 71, call; 72, attribute; 73, argument_list; 74, identifier:x0; 75, boolean_operator; 76, block; 77, else_clause; 78, call; 79, tuple; 80, call; 81, tuple; 82, identifier:np; 83, identifier:asanyarray; 84, identifier:x; 85, identifier:np; 86, identifier:atleast_1d; 87, identifier:x0; 88, identifier:x; 89, identifier:size; 90, identifier:x0; 91, identifier:size; 92, identifier:ValueError; 93, argument_list; 94, identifier:ValueError; 95, argument_list; 96, identifier:np; 97, identifier:empty_like; 98, identifier:x0; 99, keyword_argument; 100, comparison_operator:xi is not None; 101, parenthesized_expression; 102, expression_statement; 103, block; 104, attribute; 105, argument_list; 106, attribute; 107, argument_list; 108, string; 109, string; 110, identifier:dtype; 111, identifier:int; 112, identifier:xi; 113, None; 114, boolean_operator; 115, assignment; 116, raise_statement; 117, identifier:ind; 118, identifier:squeeze; 119, subscript; 120, identifier:squeeze; 121, string_content:empty input(s); 122, string_content:2-D x0 not handled yet; 123, call; 124, call; 125, subscript; 126, call; 127, call; 128, identifier:x; 129, identifier:ind; 130, identifier:isinstance; 131, argument_list; 132, attribute; 133, argument_list; 134, identifier:ind; 135, identifier:i; 136, attribute; 137, argument_list; 138, identifier:ValueError; 139, argument_list; 140, identifier:xi; 141, tuple; 142, identifier:np; 143, identifier:isfinite; 144, identifier:xi; 145, identifier:np; 146, identifier:nanargmin; 147, call; 148, string; 149, attribute; 150, attribute; 151, attribute; 152, identifier:abs; 153, argument_list; 154, string_content:x0 must NOT be None or NaN to avoid surprising None return value; 155, identifier:datetime; 156, identifier:datetime; 157, identifier:datetime; 158, identifier:date; 159, identifier:np; 160, identifier:datetime64; 161, binary_operator:x-xi; 162, identifier:x; 163, identifier:xi | 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; 5, 14; 5, 15; 5, 16; 5, 17; 5, 18; 5, 19; 5, 20; 8, 21; 8, 22; 9, 23; 10, 24; 12, 25; 14, 26; 14, 27; 15, 28; 15, 29; 17, 30; 19, 31; 19, 32; 19, 33; 20, 34; 22, 35; 22, 36; 24, 37; 24, 38; 25, 39; 25, 40; 26, 41; 26, 42; 27, 43; 28, 44; 28, 45; 29, 46; 30, 47; 30, 48; 31, 49; 31, 50; 32, 51; 32, 52; 33, 53; 34, 54; 34, 55; 35, 56; 36, 57; 38, 58; 38, 59; 40, 60; 40, 61; 41, 62; 41, 63; 42, 64; 42, 65; 43, 66; 44, 67; 44, 68; 45, 69; 45, 70; 46, 71; 48, 72; 48, 73; 52, 74; 53, 75; 53, 76; 53, 77; 54, 78; 54, 79; 55, 80; 55, 81; 58, 82; 58, 83; 59, 84; 60, 85; 60, 86; 61, 87; 62, 88; 62, 89; 64, 90; 64, 91; 66, 92; 66, 93; 71, 94; 71, 95; 72, 96; 72, 97; 73, 98; 73, 99; 75, 100; 75, 101; 76, 102; 77, 103; 78, 104; 78, 105; 80, 106; 80, 107; 93, 108; 95, 109; 99, 110; 99, 111; 100, 112; 100, 113; 101, 114; 102, 115; 103, 116; 104, 117; 104, 118; 106, 119; 106, 120; 108, 121; 109, 122; 114, 123; 114, 124; 115, 125; 115, 126; 116, 127; 119, 128; 119, 129; 123, 130; 123, 131; 124, 132; 124, 133; 125, 134; 125, 135; 126, 136; 126, 137; 127, 138; 127, 139; 131, 140; 131, 141; 132, 142; 132, 143; 133, 144; 136, 145; 136, 146; 137, 147; 139, 148; 141, 149; 141, 150; 141, 151; 147, 152; 147, 153; 148, 154; 149, 155; 149, 156; 150, 157; 150, 158; 151, 159; 151, 160; 153, 161; 161, 162; 161, 163 | def find_nearest(x, x0) -> Tuple[int, Any]:
"""
This find_nearest function does NOT assume sorted input
inputs:
x: array (float, int, datetime, h5py.Dataset) within which to search for x0
x0: singleton or array of values to search for in x
outputs:
idx: index of flattened x nearest to x0 (i.e. works with higher than 1-D arrays also)
xidx: x[idx]
Observe how bisect.bisect() gives the incorrect result!
idea based on:
http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array
"""
x = np.asanyarray(x) # for indexing upon return
x0 = np.atleast_1d(x0)
# %%
if x.size == 0 or x0.size == 0:
raise ValueError('empty input(s)')
if x0.ndim not in (0, 1):
raise ValueError('2-D x0 not handled yet')
# %%
ind = np.empty_like(x0, dtype=int)
# NOTE: not trapping IndexError (all-nan) becaues returning None can surprise with slice indexing
for i, xi in enumerate(x0):
if xi is not None and (isinstance(xi, (datetime.datetime, datetime.date, np.datetime64)) or np.isfinite(xi)):
ind[i] = np.nanargmin(abs(x-xi))
else:
raise ValueError('x0 must NOT be None or NaN to avoid surprising None return value')
return ind.squeeze()[()], x[ind].squeeze()[()] |
0, module; 1, function_definition; 2, function_name:primary_mrna; 3, parameters; 4, block; 5, identifier:entrystream; 6, default_parameter; 7, expression_statement; 8, for_statement; 9, identifier:parenttype; 10, string; 11, comment:"""
Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
This function **does not** return only mRNA features, it returns all GFF3
entry types (pragmas, features, sequences, etc). The function **does**
modify the gene features that pass through to ensure that they have at most
a single mRNA feature.
>>> reader = tag.GFF3Reader(tag.pkgdata('pdom-withseq.gff3'))
>>> filter = tag.transcript.primary_mrna(reader)
>>> for gene in tag.select.features(filter, type='gene'):
... assert gene.num_children == 1
"""; 12, identifier:entry; 13, identifier:entrystream; 14, block; 15, string_content:gene; 16, if_statement; 17, for_statement; 18, expression_statement; 19, not_operator; 20, block; 21, identifier:parent; 22, call; 23, block; 24, yield; 25, call; 26, expression_statement; 27, continue_statement; 28, attribute; 29, argument_list; 30, expression_statement; 31, if_statement; 32, expression_statement; 33, identifier:entry; 34, identifier:isinstance; 35, argument_list; 36, yield; 37, attribute; 38, identifier:features; 39, identifier:entry; 40, identifier:parenttype; 41, keyword_argument; 42, assignment; 43, comparison_operator:len(mrnas) == 0; 44, block; 45, call; 46, identifier:entry; 47, attribute; 48, identifier:entry; 49, identifier:tag; 50, identifier:select; 51, identifier:traverse; 52, True; 53, identifier:mrnas; 54, list_comprehension; 55, call; 56, integer:0; 57, continue_statement; 58, identifier:_emplace_pmrna; 59, argument_list; 60, identifier:tag; 61, identifier:Feature; 62, identifier:f; 63, for_in_clause; 64, if_clause; 65, identifier:len; 66, argument_list; 67, identifier:mrnas; 68, identifier:parent; 69, identifier:f; 70, attribute; 71, comparison_operator:f.type == 'mRNA'; 72, identifier:mrnas; 73, identifier:parent; 74, identifier:children; 75, attribute; 76, string; 77, identifier:f; 78, identifier:type; 79, string_content:mRNA | 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; 10, 15; 14, 16; 14, 17; 14, 18; 16, 19; 16, 20; 17, 21; 17, 22; 17, 23; 18, 24; 19, 25; 20, 26; 20, 27; 22, 28; 22, 29; 23, 30; 23, 31; 23, 32; 24, 33; 25, 34; 25, 35; 26, 36; 28, 37; 28, 38; 29, 39; 29, 40; 29, 41; 30, 42; 31, 43; 31, 44; 32, 45; 35, 46; 35, 47; 36, 48; 37, 49; 37, 50; 41, 51; 41, 52; 42, 53; 42, 54; 43, 55; 43, 56; 44, 57; 45, 58; 45, 59; 47, 60; 47, 61; 54, 62; 54, 63; 54, 64; 55, 65; 55, 66; 59, 67; 59, 68; 63, 69; 63, 70; 64, 71; 66, 72; 70, 73; 70, 74; 71, 75; 71, 76; 75, 77; 75, 78; 76, 79 | def primary_mrna(entrystream, parenttype='gene'):
"""
Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
This function **does not** return only mRNA features, it returns all GFF3
entry types (pragmas, features, sequences, etc). The function **does**
modify the gene features that pass through to ensure that they have at most
a single mRNA feature.
>>> reader = tag.GFF3Reader(tag.pkgdata('pdom-withseq.gff3'))
>>> filter = tag.transcript.primary_mrna(reader)
>>> for gene in tag.select.features(filter, type='gene'):
... assert gene.num_children == 1
"""
for entry in entrystream:
if not isinstance(entry, tag.Feature):
yield entry
continue
for parent in tag.select.features(entry, parenttype, traverse=True):
mrnas = [f for f in parent.children if f.type == 'mRNA']
if len(mrnas) == 0:
continue
_emplace_pmrna(mrnas, parent)
yield entry |
0, module; 1, function_definition; 2, function_name:notes; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, identifier:public_only; 15, False; 16, comment:"""
Retrieve a list of Note instances that should be shown for this
release, grouped as either new features or known issues, and sorted
first by sort_num highest to lowest and then by created date,
which is applied to both groups,
and then for new features we also sort by tag in the order specified
by Note.TAGS, with untagged notes coming first, then finally moving
any note with the fixed tag that starts with the release version to
the top, for what we call "dot fixes".
"""; 17, assignment; 18, assignment; 19, identifier:public_only; 20, block; 21, assignment; 22, assignment; 23, expression_list; 24, identifier:tag_index; 25, call; 26, identifier:notes; 27, call; 28, expression_statement; 29, identifier:known_issues; 30, list_comprehension; 31, identifier:new_features; 32, call; 33, identifier:new_features; 34, identifier:known_issues; 35, identifier:dict; 36, generator_expression; 37, attribute; 38, argument_list; 39, assignment; 40, identifier:n; 41, for_in_clause; 42, if_clause; 43, identifier:sorted; 44, argument_list; 45, tuple; 46, for_in_clause; 47, attribute; 48, identifier:order_by; 49, string; 50, string; 51, identifier:notes; 52, call; 53, identifier:n; 54, identifier:notes; 55, call; 56, call; 57, keyword_argument; 58, keyword_argument; 59, identifier:tag; 60, identifier:i; 61, pattern_list; 62, call; 63, identifier:self; 64, identifier:note_set; 65, string_content:-sort_num; 66, string_content:created; 67, attribute; 68, argument_list; 69, attribute; 70, argument_list; 71, identifier:sorted; 72, argument_list; 73, identifier:key; 74, lambda; 75, identifier:reverse; 76, True; 77, identifier:i; 78, identifier:tag; 79, identifier:enumerate; 80, argument_list; 81, identifier:notes; 82, identifier:filter; 83, keyword_argument; 84, identifier:n; 85, identifier:is_known_issue_for; 86, identifier:self; 87, generator_expression; 88, keyword_argument; 89, lambda_parameters; 90, boolean_operator; 91, attribute; 92, identifier:is_public; 93, True; 94, identifier:n; 95, for_in_clause; 96, if_clause; 97, identifier:key; 98, lambda; 99, identifier:n; 100, comparison_operator:n.tag == 'Fixed'; 101, call; 102, identifier:Note; 103, identifier:TAGS; 104, identifier:n; 105, identifier:notes; 106, not_operator; 107, lambda_parameters; 108, call; 109, attribute; 110, string; 111, attribute; 112, argument_list; 113, call; 114, identifier:note; 115, attribute; 116, argument_list; 117, identifier:n; 118, identifier:tag; 119, string_content:Fixed; 120, attribute; 121, identifier:startswith; 122, attribute; 123, attribute; 124, argument_list; 125, identifier:tag_index; 126, identifier:get; 127, attribute; 128, integer:0; 129, identifier:n; 130, identifier:note; 131, identifier:self; 132, identifier:version; 133, identifier:n; 134, identifier:is_known_issue_for; 135, identifier:self; 136, identifier:note; 137, identifier:tag | 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; 9, 18; 10, 19; 10, 20; 11, 21; 12, 22; 13, 23; 17, 24; 17, 25; 18, 26; 18, 27; 20, 28; 21, 29; 21, 30; 22, 31; 22, 32; 23, 33; 23, 34; 25, 35; 25, 36; 27, 37; 27, 38; 28, 39; 30, 40; 30, 41; 30, 42; 32, 43; 32, 44; 36, 45; 36, 46; 37, 47; 37, 48; 38, 49; 38, 50; 39, 51; 39, 52; 41, 53; 41, 54; 42, 55; 44, 56; 44, 57; 44, 58; 45, 59; 45, 60; 46, 61; 46, 62; 47, 63; 47, 64; 49, 65; 50, 66; 52, 67; 52, 68; 55, 69; 55, 70; 56, 71; 56, 72; 57, 73; 57, 74; 58, 75; 58, 76; 61, 77; 61, 78; 62, 79; 62, 80; 67, 81; 67, 82; 68, 83; 69, 84; 69, 85; 70, 86; 72, 87; 72, 88; 74, 89; 74, 90; 80, 91; 83, 92; 83, 93; 87, 94; 87, 95; 87, 96; 88, 97; 88, 98; 89, 99; 90, 100; 90, 101; 91, 102; 91, 103; 95, 104; 95, 105; 96, 106; 98, 107; 98, 108; 100, 109; 100, 110; 101, 111; 101, 112; 106, 113; 107, 114; 108, 115; 108, 116; 109, 117; 109, 118; 110, 119; 111, 120; 111, 121; 112, 122; 113, 123; 113, 124; 115, 125; 115, 126; 116, 127; 116, 128; 120, 129; 120, 130; 122, 131; 122, 132; 123, 133; 123, 134; 124, 135; 127, 136; 127, 137 | def notes(self, public_only=False):
"""
Retrieve a list of Note instances that should be shown for this
release, grouped as either new features or known issues, and sorted
first by sort_num highest to lowest and then by created date,
which is applied to both groups,
and then for new features we also sort by tag in the order specified
by Note.TAGS, with untagged notes coming first, then finally moving
any note with the fixed tag that starts with the release version to
the top, for what we call "dot fixes".
"""
tag_index = dict((tag, i) for i, tag in enumerate(Note.TAGS))
notes = self.note_set.order_by('-sort_num', 'created')
if public_only:
notes = notes.filter(is_public=True)
known_issues = [n for n in notes if n.is_known_issue_for(self)]
new_features = sorted(
sorted(
(n for n in notes if not n.is_known_issue_for(self)),
key=lambda note: tag_index.get(note.tag, 0)),
key=lambda n: n.tag == 'Fixed' and n.note.startswith(self.version),
reverse=True)
return new_features, known_issues |
0, module; 1, function_definition; 2, function_name:dispatchlist; 3, parameters; 4, block; 5, identifier:self; 6, keyword_separator; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, comment:# Here we do need to ensure that our categories are valid, cause; 15, comment:# NS just ignores the categories it doesn't recognise and returns; 16, comment:# whatever it feels like.; 17, if_statement; 18, decorated_definition; 19, return_statement; 20, identifier:author; 21, None; 22, identifier:category; 23, None; 24, identifier:subcategory; 25, None; 26, identifier:sort; 27, string; 28, comment:"""Find dispatches by certain criteria.
Parameters
----------
author : str
Name of the nation authoring the dispatch.
category : str
Dispatch's primary category.
subcategory : str
Dispatch's secondary category.
sort : str
Sort order, 'new' or 'best'.
Returns
-------
an :class:`ApiQuery` of a list of :class:`DispatchThumbnail`
"""; 29, assignment; 30, identifier:author; 31, block; 32, boolean_operator; 33, block; 34, elif_clause; 35, else_clause; 36, decorator; 37, function_definition; 38, call; 39, string_content:new; 40, identifier:params; 41, dictionary; 42, expression_statement; 43, identifier:category; 44, identifier:subcategory; 45, if_statement; 46, expression_statement; 47, identifier:category; 48, block; 49, block; 50, call; 51, function_name:result; 52, parameters; 53, block; 54, identifier:result; 55, argument_list; 56, pair; 57, assignment; 58, parenthesized_expression; 59, block; 60, assignment; 61, if_statement; 62, expression_statement; 63, raise_statement; 64, identifier:api_query; 65, argument_list; 66, identifier:_; 67, identifier:root; 68, return_statement; 69, identifier:self; 70, string; 71, identifier:sort; 72, subscript; 73, identifier:author; 74, boolean_operator; 75, raise_statement; 76, subscript; 77, string; 78, comparison_operator:category not in dispatch_categories; 79, block; 80, assignment; 81, call; 82, string; 83, dictionary_splat; 84, list_comprehension; 85, string_content:sort; 86, identifier:params; 87, string; 88, comparison_operator:category not in dispatch_categories; 89, comparison_operator:subcategory not in dispatch_categories[category]; 90, call; 91, identifier:params; 92, string; 93, interpolation; 94, string_content::; 95, interpolation; 96, identifier:category; 97, identifier:dispatch_categories; 98, raise_statement; 99, subscript; 100, identifier:category; 101, identifier:ValueError; 102, argument_list; 103, string_content:dispatchlist; 104, identifier:params; 105, call; 106, for_in_clause; 107, string_content:dispatchauthor; 108, identifier:category; 109, identifier:dispatch_categories; 110, identifier:subcategory; 111, subscript; 112, identifier:ValueError; 113, argument_list; 114, string_content:dispatchcategory; 115, identifier:category; 116, identifier:subcategory; 117, call; 118, identifier:params; 119, string; 120, string; 121, attribute; 122, argument_list; 123, identifier:elem; 124, call; 125, identifier:dispatch_categories; 126, identifier:category; 127, string; 128, identifier:ValueError; 129, argument_list; 130, string_content:dispatchcategory; 131, string_content:Cannot request subcategory without category; 132, identifier:DispatchThumbnail; 133, identifier:_from_elem; 134, identifier:elem; 135, attribute; 136, argument_list; 137, string_content:Invalid category/subcategory; 138, string; 139, identifier:root; 140, identifier:find; 141, string; 142, string_content:Invalid category; 143, string_content:DISPATCHLIST | 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; 7, 20; 7, 21; 8, 22; 8, 23; 9, 24; 9, 25; 10, 26; 10, 27; 11, 28; 12, 29; 13, 30; 13, 31; 17, 32; 17, 33; 17, 34; 17, 35; 18, 36; 18, 37; 19, 38; 27, 39; 29, 40; 29, 41; 31, 42; 32, 43; 32, 44; 33, 45; 33, 46; 34, 47; 34, 48; 35, 49; 36, 50; 37, 51; 37, 52; 37, 53; 38, 54; 38, 55; 41, 56; 42, 57; 45, 58; 45, 59; 46, 60; 48, 61; 48, 62; 49, 63; 50, 64; 50, 65; 52, 66; 52, 67; 53, 68; 55, 69; 56, 70; 56, 71; 57, 72; 57, 73; 58, 74; 59, 75; 60, 76; 60, 77; 61, 78; 61, 79; 62, 80; 63, 81; 65, 82; 65, 83; 68, 84; 70, 85; 72, 86; 72, 87; 74, 88; 74, 89; 75, 90; 76, 91; 76, 92; 77, 93; 77, 94; 77, 95; 78, 96; 78, 97; 79, 98; 80, 99; 80, 100; 81, 101; 81, 102; 82, 103; 83, 104; 84, 105; 84, 106; 87, 107; 88, 108; 88, 109; 89, 110; 89, 111; 90, 112; 90, 113; 92, 114; 93, 115; 95, 116; 98, 117; 99, 118; 99, 119; 102, 120; 105, 121; 105, 122; 106, 123; 106, 124; 111, 125; 111, 126; 113, 127; 117, 128; 117, 129; 119, 130; 120, 131; 121, 132; 121, 133; 122, 134; 124, 135; 124, 136; 127, 137; 129, 138; 135, 139; 135, 140; 136, 141; 138, 142; 141, 143 | def dispatchlist(self, *, author=None, category=None,
subcategory=None, sort='new'):
"""Find dispatches by certain criteria.
Parameters
----------
author : str
Name of the nation authoring the dispatch.
category : str
Dispatch's primary category.
subcategory : str
Dispatch's secondary category.
sort : str
Sort order, 'new' or 'best'.
Returns
-------
an :class:`ApiQuery` of a list of :class:`DispatchThumbnail`
"""
params = {'sort': sort}
if author:
params['dispatchauthor'] = author
# Here we do need to ensure that our categories are valid, cause
# NS just ignores the categories it doesn't recognise and returns
# whatever it feels like.
if category and subcategory:
if (category not in dispatch_categories or
subcategory not in dispatch_categories[category]):
raise ValueError('Invalid category/subcategory')
params['dispatchcategory'] = f'{category}:{subcategory}'
elif category:
if category not in dispatch_categories:
raise ValueError('Invalid category')
params['dispatchcategory'] = category
else:
raise ValueError('Cannot request subcategory without category')
@api_query('dispatchlist', **params)
async def result(_, root):
return [
DispatchThumbnail._from_elem(elem)
for elem in root.find('DISPATCHLIST')
]
return result(self) |
0, module; 1, function_definition; 2, function_name:have_cycle; 3, parameters; 4, type; 5, block; 6, typed_parameter; 7, identifier:frozenset; 8, expression_statement; 9, comment:# topological sort; 10, expression_statement; 11, comment:# walked nodes; 12, expression_statement; 13, comment:# all nodes of the graph; 14, expression_statement; 15, comment:# succ: preds; 16, expression_statement; 17, while_statement; 18, return_statement; 19, identifier:graph; 20, type; 21, comment:"""Perform a topologic sort to detect any cycle.
Return the set of unsortable nodes. If at least one item,
then there is cycle in given graph.
"""; 22, assignment; 23, assignment; 24, assignment; 25, assignment; 26, comparison_operator:last_walked_len != len(walked); 27, block; 28, call; 29, identifier:dict; 30, identifier:walked; 31, call; 32, identifier:nodes; 33, call; 34, identifier:preds; 35, call; 36, identifier:last_walked_len; 37, unary_operator; 38, identifier:last_walked_len; 39, call; 40, expression_statement; 41, for_statement; 42, identifier:frozenset; 43, argument_list; 44, identifier:set; 45, argument_list; 46, identifier:frozenset; 47, argument_list; 48, identifier:reversed_graph; 49, argument_list; 50, integer:1; 51, identifier:len; 52, argument_list; 53, assignment; 54, identifier:node; 55, binary_operator:nodes - walked; 56, block; 57, binary_operator:nodes - walked; 58, call; 59, identifier:graph; 60, identifier:walked; 61, identifier:last_walked_len; 62, call; 63, identifier:nodes; 64, identifier:walked; 65, if_statement; 66, identifier:nodes; 67, identifier:walked; 68, attribute; 69, argument_list; 70, identifier:len; 71, argument_list; 72, comparison_operator:len(preds.get(node, set()) - walked) == 0; 73, block; 74, identifier:it; 75, identifier:chain; 76, call; 77, call; 78, identifier:walked; 79, call; 80, integer:0; 81, expression_statement; 82, attribute; 83, argument_list; 84, attribute; 85, argument_list; 86, identifier:len; 87, argument_list; 88, call; 89, attribute; 90, identifier:from_iterable; 91, call; 92, identifier:graph; 93, identifier:keys; 94, binary_operator:preds.get(node, set()) - walked; 95, attribute; 96, argument_list; 97, identifier:it; 98, identifier:chain; 99, attribute; 100, argument_list; 101, call; 102, identifier:walked; 103, identifier:walked; 104, identifier:add; 105, identifier:node; 106, identifier:graph; 107, identifier:values; 108, attribute; 109, argument_list; 110, identifier:preds; 111, identifier:get; 112, identifier:node; 113, call; 114, identifier:set; 115, argument_list | 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; 5, 17; 5, 18; 6, 19; 6, 20; 8, 21; 10, 22; 12, 23; 14, 24; 16, 25; 17, 26; 17, 27; 18, 28; 20, 29; 22, 30; 22, 31; 23, 32; 23, 33; 24, 34; 24, 35; 25, 36; 25, 37; 26, 38; 26, 39; 27, 40; 27, 41; 28, 42; 28, 43; 31, 44; 31, 45; 33, 46; 33, 47; 35, 48; 35, 49; 37, 50; 39, 51; 39, 52; 40, 53; 41, 54; 41, 55; 41, 56; 43, 57; 47, 58; 49, 59; 52, 60; 53, 61; 53, 62; 55, 63; 55, 64; 56, 65; 57, 66; 57, 67; 58, 68; 58, 69; 62, 70; 62, 71; 65, 72; 65, 73; 68, 74; 68, 75; 69, 76; 69, 77; 71, 78; 72, 79; 72, 80; 73, 81; 76, 82; 76, 83; 77, 84; 77, 85; 79, 86; 79, 87; 81, 88; 82, 89; 82, 90; 83, 91; 84, 92; 84, 93; 87, 94; 88, 95; 88, 96; 89, 97; 89, 98; 91, 99; 91, 100; 94, 101; 94, 102; 95, 103; 95, 104; 96, 105; 99, 106; 99, 107; 101, 108; 101, 109; 108, 110; 108, 111; 109, 112; 109, 113; 113, 114; 113, 115 | def have_cycle(graph:dict) -> frozenset:
"""Perform a topologic sort to detect any cycle.
Return the set of unsortable nodes. If at least one item,
then there is cycle in given graph.
"""
# topological sort
walked = set() # walked nodes
nodes = frozenset(it.chain(it.chain.from_iterable(graph.values()), graph.keys())) # all nodes of the graph
preds = reversed_graph(graph) # succ: preds
last_walked_len = -1
while last_walked_len != len(walked):
last_walked_len = len(walked)
for node in nodes - walked:
if len(preds.get(node, set()) - walked) == 0:
walked.add(node)
return frozenset(nodes - walked) |
0, module; 1, function_definition; 2, function_name:time_pipeline; 3, parameters; 4, block; 5, identifier:iterable; 6, list_splat_pattern; 7, expression_statement; 8, if_statement; 9, comment:# if iterable is not a function, load the whole thing; 10, comment:# into a list so it can be ran over multiple times; 11, if_statement; 12, comment:# these store timestamps for time calculations; 13, expression_statement; 14, expression_statement; 15, for_statement; 16, comment:#print(results); 17, comment:#print(durations); 18, assert_statement; 19, expression_statement; 20, expression_statement; 21, comment:#print(ratios); 22, for_statement; 23, identifier:steps; 24, string; 25, call; 26, block; 27, else_clause; 28, not_operator; 29, block; 30, assignment; 31, assignment; 32, pattern_list; 33, call; 34, block; 35, comparison_operator:sum(results) > 0; 36, assignment; 37, assignment; 38, identifier:i; 39, call; 40, block; 41, string_content:This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterable:(i for i in iterable if i%5==0)
step2 = lambda iterable:(i for i in iterable if i%8==3)
step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable)
step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable)
print('filter first')
time_pipeline(l, step1, step2, step3, step4)
print('process first')
time_pipeline(l, step3, step4, step1, step2)
print('filter, process, filter, process')
time_pipeline(l, step1, step3, step2, step4)
```
Outputs:
filter first
step 1 | 2.0427s | step1 = lambda iterable:(i for i in iterable if i%5==0)
step 2 | 2.0510s | step2 = lambda iterable:(i for i in iterable if i%8==3)
step 3 | 2.4839s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable)
step 4 | 2.8446s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable)
process first
step 1 | 7.5291s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable)
step 2 | 20.6732s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable)
step 3 | 16.8470s | step1 = lambda iterable:(i for i in iterable if i%5==0)
step 4 | 16.8269s | step2 = lambda iterable:(i for i in iterable if i%8==3)
filter, process, filter, process
step 1 | 2.0528s | step1 = lambda iterable:(i for i in iterable if i%5==0)
step 2 | 3.3039s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable)
step 3 | 3.1385s | step2 = lambda iterable:(i for i in iterable if i%8==3)
step 4 | 3.1489s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable); 42, identifier:callable; 43, argument_list; 44, try_statement; 45, block; 46, identifier:callable_base; 47, expression_statement; 48, identifier:durations; 49, list; 50, identifier:results; 51, list; 52, identifier:i; 53, identifier:_; 54, identifier:enumerate; 55, argument_list; 56, expression_statement; 57, comment:#print('testing',current_tasks); 58, expression_statement; 59, comment:# run this test x number of times; 60, for_statement; 61, expression_statement; 62, if_statement; 63, call; 64, integer:0; 65, identifier:resultsum; 66, call; 67, identifier:ratios; 68, list_comprehension; 69, identifier:range; 70, argument_list; 71, try_statement; 72, expression_statement; 73, identifier:iterable; 74, block; 75, except_clause; 76, try_statement; 77, assignment; 78, identifier:steps; 79, assignment; 80, assignment; 81, identifier:t; 82, call; 83, comment:# build the generator; 84, block; 85, call; 86, comparison_operator:len(durations) == 1; 87, block; 88, else_clause; 89, identifier:sum; 90, argument_list; 91, identifier:sum; 92, argument_list; 93, binary_operator:i/resultsum; 94, for_in_clause; 95, call; 96, block; 97, except_clause; 98, call; 99, expression_statement; 100, expression_statement; 101, block; 102, block; 103, except_clause; 104, identifier:iterable; 105, call; 106, identifier:current_tasks; 107, subscript; 108, identifier:duration; 109, float:0.0; 110, identifier:range; 111, argument_list; 112, expression_statement; 113, comment:# time its execution; 114, expression_statement; 115, for_statement; 116, for_statement; 117, expression_statement; 118, attribute; 119, argument_list; 120, call; 121, integer:1; 122, expression_statement; 123, comment:#print(durations[0],durations[0]); 124, block; 125, identifier:results; 126, identifier:results; 127, identifier:i; 128, identifier:resultsum; 129, identifier:i; 130, identifier:results; 131, identifier:len; 132, argument_list; 133, expression_statement; 134, block; 135, identifier:print; 136, argument_list; 137, call; 138, assignment; 139, raise_statement; 140, expression_statement; 141, expression_statement; 142, block; 143, identifier:tuple; 144, argument_list; 145, identifier:steps; 146, slice; 147, integer:100000; 148, assignment; 149, assignment; 150, identifier:task; 151, identifier:current_tasks; 152, block; 153, identifier:i; 154, call; 155, block; 156, augmented_assignment; 157, identifier:durations; 158, identifier:append; 159, identifier:duration; 160, identifier:len; 161, argument_list; 162, call; 163, expression_statement; 164, comment:#print(durations[-1]-durations[-2],durations[-1]); 165, identifier:ratios; 166, assignment; 167, expression_statement; 168, call; 169, identifier:iter; 170, argument_list; 171, identifier:callable_base; 172, True; 173, call; 174, call; 175, assignment; 176, raise_statement; 177, identifier:iterable; 178, binary_operator:i+1; 179, identifier:test_generator; 180, conditional_expression:iter(iterable()) if callable_base else iter(iterable); 181, identifier:start; 182, call; 183, expression_statement; 184, subscript; 185, argument_list; 186, pass_statement; 187, identifier:duration; 188, binary_operator:ts() - start; 189, identifier:durations; 190, attribute; 191, argument_list; 192, call; 193, identifier:s; 194, call; 195, assignment; 196, attribute; 197, argument_list; 198, call; 199, identifier:TypeError; 200, argument_list; 201, identifier:iter; 202, argument_list; 203, identifier:callable_base; 204, False; 205, call; 206, identifier:i; 207, integer:1; 208, call; 209, identifier:callable_base; 210, call; 211, identifier:ts; 212, argument_list; 213, assignment; 214, identifier:current_tasks; 215, unary_operator; 216, identifier:test_generator; 217, call; 218, identifier:start; 219, identifier:results; 220, identifier:append; 221, subscript; 222, attribute; 223, argument_list; 224, attribute; 225, argument_list; 226, identifier:s; 227, call; 228, string; 229, identifier:format; 230, binary_operator:i+1; 231, subscript; 232, identifier:s; 233, identifier:iterable; 234, argument_list; 235, string; 236, identifier:iterable; 237, identifier:TypeError; 238, argument_list; 239, identifier:iter; 240, argument_list; 241, identifier:iter; 242, argument_list; 243, identifier:test_generator; 244, call; 245, integer:1; 246, identifier:ts; 247, argument_list; 248, identifier:durations; 249, integer:0; 250, identifier:results; 251, identifier:append; 252, binary_operator:durations[-1]-durations[-2]; 253, subscript; 254, identifier:strip; 255, attribute; 256, argument_list; 257, string_content:step {} | {:2.4f}s | {}; 258, identifier:i; 259, integer:1; 260, identifier:durations; 261, identifier:i; 262, string_content:time_pipeline needs the first argument to be an iterable or a function that produces an iterable.; 263, string; 264, call; 265, identifier:iterable; 266, identifier:task; 267, argument_list; 268, subscript; 269, subscript; 270, call; 271, integer:0; 272, call; 273, identifier:strip; 274, string_content:time_pipeline needs the first argument to be an iterable or a function that produces an iterable.; 275, identifier:iterable; 276, argument_list; 277, identifier:test_generator; 278, identifier:durations; 279, unary_operator; 280, identifier:durations; 281, unary_operator; 282, attribute; 283, argument_list; 284, identifier:repr; 285, argument_list; 286, integer:1; 287, integer:2; 288, call; 289, identifier:splitlines; 290, subscript; 291, identifier:getsource; 292, argument_list; 293, identifier:steps; 294, identifier:i; 295, subscript; 296, identifier:steps; 297, identifier:i | 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; 6, 23; 7, 24; 8, 25; 8, 26; 8, 27; 11, 28; 11, 29; 13, 30; 14, 31; 15, 32; 15, 33; 15, 34; 18, 35; 19, 36; 20, 37; 22, 38; 22, 39; 22, 40; 24, 41; 25, 42; 25, 43; 26, 44; 27, 45; 28, 46; 29, 47; 30, 48; 30, 49; 31, 50; 31, 51; 32, 52; 32, 53; 33, 54; 33, 55; 34, 56; 34, 57; 34, 58; 34, 59; 34, 60; 34, 61; 34, 62; 35, 63; 35, 64; 36, 65; 36, 66; 37, 67; 37, 68; 39, 69; 39, 70; 40, 71; 40, 72; 43, 73; 44, 74; 44, 75; 45, 76; 47, 77; 55, 78; 56, 79; 58, 80; 60, 81; 60, 82; 60, 83; 60, 84; 61, 85; 62, 86; 62, 87; 62, 88; 63, 89; 63, 90; 66, 91; 66, 92; 68, 93; 68, 94; 70, 95; 71, 96; 71, 97; 72, 98; 74, 99; 74, 100; 75, 101; 76, 102; 76, 103; 77, 104; 77, 105; 79, 106; 79, 107; 80, 108; 80, 109; 82, 110; 82, 111; 84, 112; 84, 113; 84, 114; 84, 115; 84, 116; 84, 117; 85, 118; 85, 119; 86, 120; 86, 121; 87, 122; 87, 123; 88, 124; 90, 125; 92, 126; 93, 127; 93, 128; 94, 129; 94, 130; 95, 131; 95, 132; 96, 133; 97, 134; 98, 135; 98, 136; 99, 137; 100, 138; 101, 139; 102, 140; 102, 141; 103, 142; 105, 143; 105, 144; 107, 145; 107, 146; 111, 147; 112, 148; 114, 149; 115, 150; 115, 151; 115, 152; 116, 153; 116, 154; 116, 155; 117, 156; 118, 157; 118, 158; 119, 159; 120, 160; 120, 161; 122, 162; 124, 163; 124, 164; 132, 165; 133, 166; 134, 167; 136, 168; 137, 169; 137, 170; 138, 171; 138, 172; 139, 173; 140, 174; 141, 175; 142, 176; 144, 177; 146, 178; 148, 179; 148, 180; 149, 181; 149, 182; 152, 183; 154, 184; 154, 185; 155, 186; 156, 187; 156, 188; 161, 189; 162, 190; 162, 191; 163, 192; 166, 193; 166, 194; 167, 195; 168, 196; 168, 197; 170, 198; 173, 199; 173, 200; 174, 201; 174, 202; 175, 203; 175, 204; 176, 205; 178, 206; 178, 207; 180, 208; 180, 209; 180, 210; 182, 211; 182, 212; 183, 213; 184, 214; 184, 215; 185, 216; 188, 217; 188, 218; 190, 219; 190, 220; 191, 221; 192, 222; 192, 223; 194, 224; 194, 225; 195, 226; 195, 227; 196, 228; 196, 229; 197, 230; 197, 231; 197, 232; 198, 233; 198, 234; 200, 235; 202, 236; 205, 237; 205, 238; 208, 239; 208, 240; 210, 241; 210, 242; 213, 243; 213, 244; 215, 245; 217, 246; 217, 247; 221, 248; 221, 249; 222, 250; 222, 251; 223, 252; 224, 253; 224, 254; 227, 255; 227, 256; 228, 257; 230, 258; 230, 259; 231, 260; 231, 261; 235, 262; 238, 263; 240, 264; 242, 265; 244, 266; 244, 267; 252, 268; 252, 269; 253, 270; 253, 271; 255, 272; 255, 273; 263, 274; 264, 275; 264, 276; 267, 277; 268, 278; 268, 279; 269, 280; 269, 281; 270, 282; 270, 283; 272, 284; 272, 285; 279, 286; 281, 287; 282, 288; 282, 289; 285, 290; 288, 291; 288, 292; 290, 293; 290, 294; 292, 295; 295, 296; 295, 297 | def time_pipeline(iterable, *steps):
'''
This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterable:(i for i in iterable if i%5==0)
step2 = lambda iterable:(i for i in iterable if i%8==3)
step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable)
step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable)
print('filter first')
time_pipeline(l, step1, step2, step3, step4)
print('process first')
time_pipeline(l, step3, step4, step1, step2)
print('filter, process, filter, process')
time_pipeline(l, step1, step3, step2, step4)
```
Outputs:
filter first
step 1 | 2.0427s | step1 = lambda iterable:(i for i in iterable if i%5==0)
step 2 | 2.0510s | step2 = lambda iterable:(i for i in iterable if i%8==3)
step 3 | 2.4839s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable)
step 4 | 2.8446s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable)
process first
step 1 | 7.5291s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable)
step 2 | 20.6732s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable)
step 3 | 16.8470s | step1 = lambda iterable:(i for i in iterable if i%5==0)
step 4 | 16.8269s | step2 = lambda iterable:(i for i in iterable if i%8==3)
filter, process, filter, process
step 1 | 2.0528s | step1 = lambda iterable:(i for i in iterable if i%5==0)
step 2 | 3.3039s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable)
step 3 | 3.1385s | step2 = lambda iterable:(i for i in iterable if i%8==3)
step 4 | 3.1489s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable)
'''
if callable(iterable):
try:
iter(iterable())
callable_base = True
except:
raise TypeError('time_pipeline needs the first argument to be an iterable or a function that produces an iterable.')
else:
try:
iter(iterable)
callable_base = False
except:
raise TypeError('time_pipeline needs the first argument to be an iterable or a function that produces an iterable.')
# if iterable is not a function, load the whole thing
# into a list so it can be ran over multiple times
if not callable_base:
iterable = tuple(iterable)
# these store timestamps for time calculations
durations = []
results = []
for i,_ in enumerate(steps):
current_tasks = steps[:i+1]
#print('testing',current_tasks)
duration = 0.0
# run this test x number of times
for t in range(100000):
# build the generator
test_generator = iter(iterable()) if callable_base else iter(iterable)
# time its execution
start = ts()
for task in current_tasks:
test_generator = task(test_generator)
for i in current_tasks[-1](test_generator):
pass
duration += ts() - start
durations.append(duration)
if len(durations) == 1:
results.append(durations[0])
#print(durations[0],durations[0])
else:
results.append(durations[-1]-durations[-2])
#print(durations[-1]-durations[-2],durations[-1])
#print(results)
#print(durations)
assert sum(results) > 0
resultsum = sum(results)
ratios = [i/resultsum for i in results]
#print(ratios)
for i in range(len(ratios)):
try:
s = getsource(steps[i]).splitlines()[0].strip()
except:
s = repr(steps[i]).strip()
print('step {} | {:2.4f}s | {}'.format(i+1, durations[i], s)) |
0, module; 1, function_definition; 2, function_name:sort_matches; 3, parameters; 4, block; 5, identifier:matches; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, string; 11, assignment; 12, assignment; 13, list_comprehension; 14, string_content:Sorts a ``list`` of matches best to worst; 15, identifier:multipliers; 16, dictionary; 17, identifier:matches; 18, list_comprehension; 19, subscript; 20, for_in_clause; 21, pair; 22, pair; 23, pair; 24, pair; 25, tuple; 26, for_in_clause; 27, identifier:x; 28, integer:1; 29, identifier:x; 30, call; 31, string; 32, binary_operator:10**5; 33, string; 34, binary_operator:10**4; 35, string; 36, binary_operator:10**2; 37, string; 38, integer:1; 39, binary_operator:multipliers[x.type]*(x.amount if x.amount else 1); 40, identifier:x; 41, identifier:x; 42, identifier:matches; 43, identifier:sorted; 44, argument_list; 45, string_content:exact; 46, integer:10; 47, integer:5; 48, string_content:fname; 49, integer:10; 50, integer:4; 51, string_content:fuzzy; 52, integer:10; 53, integer:2; 54, string_content:fuzzy_fragment; 55, subscript; 56, parenthesized_expression; 57, identifier:matches; 58, keyword_argument; 59, identifier:multipliers; 60, attribute; 61, conditional_expression:x.amount if x.amount else 1; 62, identifier:reverse; 63, True; 64, identifier:x; 65, identifier:type; 66, attribute; 67, attribute; 68, integer:1; 69, identifier:x; 70, identifier:amount; 71, identifier:x; 72, identifier:amount | 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; 10, 14; 11, 15; 11, 16; 12, 17; 12, 18; 13, 19; 13, 20; 16, 21; 16, 22; 16, 23; 16, 24; 18, 25; 18, 26; 19, 27; 19, 28; 20, 29; 20, 30; 21, 31; 21, 32; 22, 33; 22, 34; 23, 35; 23, 36; 24, 37; 24, 38; 25, 39; 25, 40; 26, 41; 26, 42; 30, 43; 30, 44; 31, 45; 32, 46; 32, 47; 33, 48; 34, 49; 34, 50; 35, 51; 36, 52; 36, 53; 37, 54; 39, 55; 39, 56; 44, 57; 44, 58; 55, 59; 55, 60; 56, 61; 58, 62; 58, 63; 60, 64; 60, 65; 61, 66; 61, 67; 61, 68; 66, 69; 66, 70; 67, 71; 67, 72 | def sort_matches(matches):
'''Sorts a ``list`` of matches best to worst'''
multipliers = {'exact':10**5,'fname':10**4,'fuzzy':10**2,'fuzzy_fragment':1}
matches = [(multipliers[x.type]*(x.amount if x.amount else 1),x) for x in matches]
return [x[1] for x in sorted(matches,reverse=True)] |
0, module; 1, function_definition; 2, function_name:_get_sorted_iterator; 3, parameters; 4, block; 5, identifier:self; 6, identifier:iterator; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, import_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, comment:"""
Get the iterator over the sorted items.
This function decides whether the items can be sorted in memory or on disk.
:return:
"""; 15, assignment; 16, comparison_operator:len(lines) < self.max_lines; 17, block; 18, dotted_name; 19, assignment; 20, assignment; 21, call; 22, identifier:lines; 23, call; 24, call; 25, attribute; 26, return_statement; 27, identifier:tempfile; 28, identifier:tmp_dir; 29, call; 30, identifier:fnames; 31, call; 32, identifier:SortedIteratorMerger; 33, argument_list; 34, identifier:list; 35, argument_list; 36, identifier:len; 37, argument_list; 38, identifier:self; 39, identifier:max_lines; 40, call; 41, attribute; 42, argument_list; 43, attribute; 44, argument_list; 45, list_comprehension; 46, attribute; 47, call; 48, identifier:lines; 49, identifier:iter; 50, argument_list; 51, identifier:tempfile; 52, identifier:mkdtemp; 53, identifier:self; 54, identifier:_split; 55, call; 56, identifier:tmp_dir; 57, call; 58, for_in_clause; 59, identifier:self; 60, identifier:key; 61, identifier:next; 62, argument_list; 63, call; 64, identifier:chain; 65, argument_list; 66, identifier:unpickle_iter; 67, argument_list; 68, identifier:fname; 69, identifier:fnames; 70, identifier:iterator; 71, identifier:sorted; 72, argument_list; 73, list; 74, identifier:iterator; 75, call; 76, identifier:lines; 77, keyword_argument; 78, identifier:lines; 79, identifier:open; 80, argument_list; 81, identifier:key; 82, attribute; 83, identifier:fname; 84, string; 85, identifier:self; 86, identifier:key; 87, string_content:rb | 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; 10, 18; 11, 19; 12, 20; 13, 21; 15, 22; 15, 23; 16, 24; 16, 25; 17, 26; 18, 27; 19, 28; 19, 29; 20, 30; 20, 31; 21, 32; 21, 33; 23, 34; 23, 35; 24, 36; 24, 37; 25, 38; 25, 39; 26, 40; 29, 41; 29, 42; 31, 43; 31, 44; 33, 45; 33, 46; 35, 47; 37, 48; 40, 49; 40, 50; 41, 51; 41, 52; 43, 53; 43, 54; 44, 55; 44, 56; 45, 57; 45, 58; 46, 59; 46, 60; 47, 61; 47, 62; 50, 63; 55, 64; 55, 65; 57, 66; 57, 67; 58, 68; 58, 69; 62, 70; 63, 71; 63, 72; 65, 73; 65, 74; 67, 75; 72, 76; 72, 77; 73, 78; 75, 79; 75, 80; 77, 81; 77, 82; 80, 83; 80, 84; 82, 85; 82, 86; 84, 87 | def _get_sorted_iterator(self, iterator):
"""
Get the iterator over the sorted items.
This function decides whether the items can be sorted in memory or on disk.
:return:
"""
lines = list(next(iterator))
if len(lines) < self.max_lines:
return iter(sorted(lines, key=self.key))
import tempfile
tmp_dir = tempfile.mkdtemp()
fnames = self._split(chain([lines], iterator), tmp_dir)
return SortedIteratorMerger([unpickle_iter(open(fname, 'rb')) for fname in fnames], self.key) |
0, module; 1, function_definition; 2, function_name:_split; 3, parameters; 4, block; 5, identifier:self; 6, identifier:iterator; 7, identifier:tmp_dir; 8, expression_statement; 9, expression_statement; 10, for_statement; 11, return_statement; 12, comment:"""
Splits the file into several chunks.
If the original file is too big to fit in the allocated space, the sorting will be split into several chunks,
then merged.
:param tmp_dir: Where to put the intermediate sorted results.
:param orig_lines: The lines read before running out of space.
:return: The names of the intermediate files.
"""; 13, assignment; 14, pattern_list; 15, call; 16, block; 17, identifier:fnames; 18, identifier:fnames; 19, list; 20, identifier:i; 21, identifier:lines; 22, identifier:enumerate; 23, argument_list; 24, expression_statement; 25, expression_statement; 26, expression_statement; 27, expression_statement; 28, if_statement; 29, identifier:iterator; 30, assignment; 31, assignment; 32, call; 33, call; 34, comparison_operator:len(lines) < self.max_lines; 35, block; 36, identifier:lines; 37, call; 38, identifier:out_fname; 39, call; 40, attribute; 41, argument_list; 42, attribute; 43, argument_list; 44, call; 45, attribute; 46, break_statement; 47, identifier:list; 48, argument_list; 49, attribute; 50, argument_list; 51, identifier:self; 52, identifier:_write; 53, identifier:lines; 54, identifier:out_fname; 55, identifier:fnames; 56, identifier:append; 57, identifier:out_fname; 58, identifier:len; 59, argument_list; 60, identifier:self; 61, identifier:max_lines; 62, identifier:lines; 63, attribute; 64, identifier:join; 65, identifier:tmp_dir; 66, call; 67, identifier:lines; 68, identifier:os; 69, identifier:path; 70, attribute; 71, argument_list; 72, attribute; 73, identifier:format; 74, binary_operator:i + 1; 75, identifier:self; 76, identifier:TMP_FNAME; 77, identifier:i; 78, integer:1 | 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; 10, 16; 11, 17; 13, 18; 13, 19; 14, 20; 14, 21; 15, 22; 15, 23; 16, 24; 16, 25; 16, 26; 16, 27; 16, 28; 23, 29; 24, 30; 25, 31; 26, 32; 27, 33; 28, 34; 28, 35; 30, 36; 30, 37; 31, 38; 31, 39; 32, 40; 32, 41; 33, 42; 33, 43; 34, 44; 34, 45; 35, 46; 37, 47; 37, 48; 39, 49; 39, 50; 40, 51; 40, 52; 41, 53; 41, 54; 42, 55; 42, 56; 43, 57; 44, 58; 44, 59; 45, 60; 45, 61; 48, 62; 49, 63; 49, 64; 50, 65; 50, 66; 59, 67; 63, 68; 63, 69; 66, 70; 66, 71; 70, 72; 70, 73; 71, 74; 72, 75; 72, 76; 74, 77; 74, 78 | def _split(self, iterator, tmp_dir):
"""
Splits the file into several chunks.
If the original file is too big to fit in the allocated space, the sorting will be split into several chunks,
then merged.
:param tmp_dir: Where to put the intermediate sorted results.
:param orig_lines: The lines read before running out of space.
:return: The names of the intermediate files.
"""
fnames = []
for i, lines in enumerate(iterator):
lines = list(lines)
out_fname = os.path.join(tmp_dir, self.TMP_FNAME.format(i + 1))
self._write(lines, out_fname)
fnames.append(out_fname)
if len(lines) < self.max_lines:
break
return fnames |
0, module; 1, function_definition; 2, function_name:_write; 3, parameters; 4, block; 5, identifier:self; 6, identifier:lines; 7, identifier:fname; 8, expression_statement; 9, with_statement; 10, comment:"""
Writes a intermediate temporary sorted file
:param lines: The lines to write.
:param fname: The name of the temporary file.
:return:
"""; 11, with_clause; 12, block; 13, with_item; 14, for_statement; 15, as_pattern; 16, identifier:line; 17, call; 18, block; 19, call; 20, as_pattern_target; 21, identifier:sorted; 22, argument_list; 23, expression_statement; 24, identifier:open; 25, argument_list; 26, identifier:out_fhndl; 27, identifier:lines; 28, keyword_argument; 29, call; 30, identifier:fname; 31, string; 32, identifier:key; 33, attribute; 34, attribute; 35, argument_list; 36, string_content:wb; 37, identifier:self; 38, identifier:key; 39, identifier:pickle; 40, identifier:dump; 41, identifier:line; 42, identifier:out_fhndl | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 8, 10; 9, 11; 9, 12; 11, 13; 12, 14; 13, 15; 14, 16; 14, 17; 14, 18; 15, 19; 15, 20; 17, 21; 17, 22; 18, 23; 19, 24; 19, 25; 20, 26; 22, 27; 22, 28; 23, 29; 25, 30; 25, 31; 28, 32; 28, 33; 29, 34; 29, 35; 31, 36; 33, 37; 33, 38; 34, 39; 34, 40; 35, 41; 35, 42 | def _write(self, lines, fname):
"""
Writes a intermediate temporary sorted file
:param lines: The lines to write.
:param fname: The name of the temporary file.
:return:
"""
with open(fname, 'wb') as out_fhndl:
for line in sorted(lines, key=self.key):
pickle.dump(line, out_fhndl) |
0, module; 1, function_definition; 2, function_name:add; 3, parameters; 4, block; 5, identifier:self; 6, identifier:interval; 7, identifier:offset; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, comment:"""
The added interval must be overlapping or beyond the last stored interval ie. added in sorted order.
:param interval: interval to add
:param offset: full virtual offset to add
:return:
"""; 12, assignment; 13, comparison_operator:len(self.starts) > 0; 14, block; 15, else_clause; 16, pattern_list; 17, call; 18, call; 19, integer:0; 20, if_statement; 21, expression_statement; 22, expression_statement; 23, block; 24, identifier:start; 25, identifier:stop; 26, attribute; 27, argument_list; 28, identifier:len; 29, argument_list; 30, boolean_operator; 31, block; 32, assignment; 33, augmented_assignment; 34, expression_statement; 35, expression_statement; 36, expression_statement; 37, identifier:self; 38, identifier:get_start_stop; 39, identifier:interval; 40, attribute; 41, comparison_operator:start < self.starts[-1]; 42, comparison_operator:offset <= self.offsets[-1][1]; 43, raise_statement; 44, subscript; 45, identifier:offset; 46, subscript; 47, integer:1; 48, call; 49, call; 50, call; 51, identifier:self; 52, identifier:starts; 53, identifier:start; 54, subscript; 55, identifier:offset; 56, subscript; 57, call; 58, subscript; 59, integer:1; 60, subscript; 61, integer:2; 62, attribute; 63, argument_list; 64, attribute; 65, argument_list; 66, attribute; 67, argument_list; 68, attribute; 69, unary_operator; 70, subscript; 71, integer:1; 72, identifier:ValueError; 73, argument_list; 74, attribute; 75, unary_operator; 76, attribute; 77, unary_operator; 78, attribute; 79, identifier:append; 80, identifier:start; 81, attribute; 82, identifier:append; 83, identifier:stop; 84, attribute; 85, identifier:append; 86, list; 87, identifier:self; 88, identifier:starts; 89, integer:1; 90, attribute; 91, unary_operator; 92, string; 93, identifier:self; 94, identifier:offsets; 95, integer:1; 96, identifier:self; 97, identifier:offsets; 98, integer:1; 99, identifier:self; 100, identifier:starts; 101, identifier:self; 102, identifier:stops; 103, identifier:self; 104, identifier:offsets; 105, identifier:offset; 106, identifier:offset; 107, integer:1; 108, identifier:self; 109, identifier:offsets; 110, integer:1; 111, string_content:intervals and offsets must be added in-order | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 8, 11; 9, 12; 10, 13; 10, 14; 10, 15; 12, 16; 12, 17; 13, 18; 13, 19; 14, 20; 14, 21; 14, 22; 15, 23; 16, 24; 16, 25; 17, 26; 17, 27; 18, 28; 18, 29; 20, 30; 20, 31; 21, 32; 22, 33; 23, 34; 23, 35; 23, 36; 26, 37; 26, 38; 27, 39; 29, 40; 30, 41; 30, 42; 31, 43; 32, 44; 32, 45; 33, 46; 33, 47; 34, 48; 35, 49; 36, 50; 40, 51; 40, 52; 41, 53; 41, 54; 42, 55; 42, 56; 43, 57; 44, 58; 44, 59; 46, 60; 46, 61; 48, 62; 48, 63; 49, 64; 49, 65; 50, 66; 50, 67; 54, 68; 54, 69; 56, 70; 56, 71; 57, 72; 57, 73; 58, 74; 58, 75; 60, 76; 60, 77; 62, 78; 62, 79; 63, 80; 64, 81; 64, 82; 65, 83; 66, 84; 66, 85; 67, 86; 68, 87; 68, 88; 69, 89; 70, 90; 70, 91; 73, 92; 74, 93; 74, 94; 75, 95; 76, 96; 76, 97; 77, 98; 78, 99; 78, 100; 81, 101; 81, 102; 84, 103; 84, 104; 86, 105; 86, 106; 86, 107; 90, 108; 90, 109; 91, 110; 92, 111 | def add(self, interval, offset):
"""
The added interval must be overlapping or beyond the last stored interval ie. added in sorted order.
:param interval: interval to add
:param offset: full virtual offset to add
:return:
"""
start, stop = self.get_start_stop(interval)
if len(self.starts) > 0:
if start < self.starts[-1] or offset <= self.offsets[-1][1]:
raise ValueError('intervals and offsets must be added in-order')
self.offsets[-1][1] = offset
self.offsets[-1][2] += 1
else:
self.starts.append(start)
self.stops.append(stop)
self.offsets.append([offset, offset, 1]) |
0, module; 1, function_definition; 2, function_name:get_collection_documents_generator; 3, parameters; 4, block; 5, identifier:client; 6, identifier:database_name; 7, identifier:collection_name; 8, identifier:spec; 9, identifier:latest_n; 10, identifier:sort_key; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, if_statement; 16, for_statement; 17, comment:"""
This is a python generator that yields tweets stored in a mongodb collection.
Tweet "created_at" field is assumed to have been stored in the format supported by MongoDB.
Inputs: - client: A pymongo MongoClient object.
- database_name: The name of a Mongo database as a string.
- collection_name: The name of the tweet collection as a string.
- spec: A python dictionary that defines higher query arguments.
- latest_n: The number of latest results we require from the mongo document collection.
- sort_key: A field name according to which we will sort in ascending order.
Yields: - document: A document in python dictionary (json) format.
"""; 18, assignment; 19, assignment; 20, call; 21, comparison_operator:latest_n is not None; 22, block; 23, else_clause; 24, identifier:document; 25, identifier:cursor; 26, block; 27, identifier:mongo_database; 28, subscript; 29, identifier:collection; 30, subscript; 31, attribute; 32, argument_list; 33, identifier:latest_n; 34, None; 35, expression_statement; 36, if_statement; 37, expression_statement; 38, expression_statement; 39, block; 40, expression_statement; 41, identifier:client; 42, identifier:database_name; 43, identifier:mongo_database; 44, identifier:collection_name; 45, identifier:collection; 46, identifier:create_index; 47, identifier:sort_key; 48, assignment; 49, comparison_operator:collection.count() - latest_n < 0; 50, block; 51, assignment; 52, assignment; 53, expression_statement; 54, yield; 55, identifier:skip_n; 56, binary_operator:collection.count() - latest_n; 57, binary_operator:collection.count() - latest_n; 58, integer:0; 59, expression_statement; 60, identifier:cursor; 61, call; 62, identifier:cursor; 63, subscript; 64, assignment; 65, identifier:document; 66, call; 67, identifier:latest_n; 68, call; 69, identifier:latest_n; 70, assignment; 71, attribute; 72, argument_list; 73, identifier:cursor; 74, slice; 75, identifier:cursor; 76, call; 77, attribute; 78, argument_list; 79, attribute; 80, argument_list; 81, identifier:skip_n; 82, integer:0; 83, call; 84, identifier:sort; 85, list; 86, identifier:skip_n; 87, attribute; 88, argument_list; 89, identifier:collection; 90, identifier:count; 91, identifier:collection; 92, identifier:count; 93, attribute; 94, argument_list; 95, tuple; 96, call; 97, identifier:sort; 98, list; 99, identifier:collection; 100, identifier:find; 101, keyword_argument; 102, identifier:sort_key; 103, identifier:ASCENDING; 104, attribute; 105, argument_list; 106, tuple; 107, identifier:filter; 108, identifier:spec; 109, identifier:collection; 110, identifier:find; 111, keyword_argument; 112, identifier:sort_key; 113, identifier:ASCENDING; 114, identifier:filter; 115, identifier:spec | 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; 11, 17; 12, 18; 13, 19; 14, 20; 15, 21; 15, 22; 15, 23; 16, 24; 16, 25; 16, 26; 18, 27; 18, 28; 19, 29; 19, 30; 20, 31; 20, 32; 21, 33; 21, 34; 22, 35; 22, 36; 22, 37; 22, 38; 23, 39; 26, 40; 28, 41; 28, 42; 30, 43; 30, 44; 31, 45; 31, 46; 32, 47; 35, 48; 36, 49; 36, 50; 37, 51; 38, 52; 39, 53; 40, 54; 48, 55; 48, 56; 49, 57; 49, 58; 50, 59; 51, 60; 51, 61; 52, 62; 52, 63; 53, 64; 54, 65; 56, 66; 56, 67; 57, 68; 57, 69; 59, 70; 61, 71; 61, 72; 63, 73; 63, 74; 64, 75; 64, 76; 66, 77; 66, 78; 68, 79; 68, 80; 70, 81; 70, 82; 71, 83; 71, 84; 72, 85; 74, 86; 76, 87; 76, 88; 77, 89; 77, 90; 79, 91; 79, 92; 83, 93; 83, 94; 85, 95; 87, 96; 87, 97; 88, 98; 93, 99; 93, 100; 94, 101; 95, 102; 95, 103; 96, 104; 96, 105; 98, 106; 101, 107; 101, 108; 104, 109; 104, 110; 105, 111; 106, 112; 106, 113; 111, 114; 111, 115 | def get_collection_documents_generator(client, database_name, collection_name, spec, latest_n, sort_key):
"""
This is a python generator that yields tweets stored in a mongodb collection.
Tweet "created_at" field is assumed to have been stored in the format supported by MongoDB.
Inputs: - client: A pymongo MongoClient object.
- database_name: The name of a Mongo database as a string.
- collection_name: The name of the tweet collection as a string.
- spec: A python dictionary that defines higher query arguments.
- latest_n: The number of latest results we require from the mongo document collection.
- sort_key: A field name according to which we will sort in ascending order.
Yields: - document: A document in python dictionary (json) format.
"""
mongo_database = client[database_name]
collection = mongo_database[collection_name]
collection.create_index(sort_key)
if latest_n is not None:
skip_n = collection.count() - latest_n
if collection.count() - latest_n < 0:
skip_n = 0
cursor = collection.find(filter=spec).sort([(sort_key, ASCENDING), ])
cursor = cursor[skip_n:]
else:
cursor = collection.find(filter=spec).sort([(sort_key, ASCENDING), ])
for document in cursor:
yield document |
0, module; 1, function_definition; 2, function_name:save; 3, parameters; 4, block; 5, identifier:self; 6, list_splat_pattern; 7, dictionary_splat_pattern; 8, expression_statement; 9, if_statement; 10, if_statement; 11, expression_statement; 12, identifier:args; 13, identifier:kwargs; 14, comment:"""
Store a string representation of content_object as target
and actor name for fast retrieval and sorting.
"""; 15, not_operator; 16, block; 17, not_operator; 18, block; 19, call; 20, attribute; 21, expression_statement; 22, attribute; 23, expression_statement; 24, attribute; 25, argument_list; 26, identifier:self; 27, identifier:target; 28, assignment; 29, identifier:self; 30, identifier:actor_name; 31, assignment; 32, call; 33, identifier:save; 34, attribute; 35, call; 36, attribute; 37, call; 38, identifier:super; 39, argument_list; 40, identifier:self; 41, identifier:target; 42, identifier:str; 43, argument_list; 44, identifier:self; 45, identifier:actor_name; 46, identifier:str; 47, argument_list; 48, identifier:Activity; 49, identifier:self; 50, attribute; 51, attribute; 52, identifier:self; 53, identifier:content_object; 54, identifier:self; 55, identifier:actor | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 7, 13; 8, 14; 9, 15; 9, 16; 10, 17; 10, 18; 11, 19; 15, 20; 16, 21; 17, 22; 18, 23; 19, 24; 19, 25; 20, 26; 20, 27; 21, 28; 22, 29; 22, 30; 23, 31; 24, 32; 24, 33; 28, 34; 28, 35; 31, 36; 31, 37; 32, 38; 32, 39; 34, 40; 34, 41; 35, 42; 35, 43; 36, 44; 36, 45; 37, 46; 37, 47; 39, 48; 39, 49; 43, 50; 47, 51; 50, 52; 50, 53; 51, 54; 51, 55 | def save(self, *args, **kwargs):
"""
Store a string representation of content_object as target
and actor name for fast retrieval and sorting.
"""
if not self.target:
self.target = str(self.content_object)
if not self.actor_name:
self.actor_name = str(self.actor)
super(Activity, self).save() |
0, module; 1, function_definition; 2, function_name:_sort_modules; 3, parameters; 4, block; 5, identifier:mods; 6, expression_statement; 7, function_definition; 8, return_statement; 9, comment:""" Always sort `index` or `README` as first filename in list. """; 10, function_name:compare; 11, parameters; 12, block; 13, call; 14, identifier:x; 15, identifier:y; 16, expression_statement; 17, expression_statement; 18, if_statement; 19, if_statement; 20, if_statement; 21, return_statement; 22, identifier:sorted; 23, argument_list; 24, assignment; 25, assignment; 26, comparison_operator:x == y; 27, block; 28, comparison_operator:y.stem == "__init__.py"; 29, block; 30, boolean_operator; 31, block; 32, integer:1; 33, identifier:mods; 34, keyword_argument; 35, identifier:x; 36, subscript; 37, identifier:y; 38, subscript; 39, identifier:x; 40, identifier:y; 41, return_statement; 42, attribute; 43, string:"__init__.py"; 44, return_statement; 45, comparison_operator:x.stem == "__init__.py"; 46, comparison_operator:x < y; 47, return_statement; 48, identifier:key; 49, call; 50, identifier:x; 51, integer:1; 52, identifier:y; 53, integer:1; 54, integer:0; 55, identifier:y; 56, identifier:stem; 57, integer:1; 58, attribute; 59, string:"__init__.py"; 60, identifier:x; 61, identifier:y; 62, unary_operator; 63, identifier:cmp_to_key; 64, argument_list; 65, identifier:x; 66, identifier:stem; 67, integer:1; 68, identifier:compare | 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; 11, 15; 12, 16; 12, 17; 12, 18; 12, 19; 12, 20; 12, 21; 13, 22; 13, 23; 16, 24; 17, 25; 18, 26; 18, 27; 19, 28; 19, 29; 20, 30; 20, 31; 21, 32; 23, 33; 23, 34; 24, 35; 24, 36; 25, 37; 25, 38; 26, 39; 26, 40; 27, 41; 28, 42; 28, 43; 29, 44; 30, 45; 30, 46; 31, 47; 34, 48; 34, 49; 36, 50; 36, 51; 38, 52; 38, 53; 41, 54; 42, 55; 42, 56; 44, 57; 45, 58; 45, 59; 46, 60; 46, 61; 47, 62; 49, 63; 49, 64; 58, 65; 58, 66; 62, 67; 64, 68 | def _sort_modules(mods):
""" Always sort `index` or `README` as first filename in list. """
def compare(x, y):
x = x[1]
y = y[1]
if x == y:
return 0
if y.stem == "__init__.py":
return 1
if x.stem == "__init__.py" or x < y:
return -1
return 1
return sorted(mods, key=cmp_to_key(compare)) |
0, module; 1, function_definition; 2, function_name:_sort_results; 3, parameters; 4, block; 5, identifier:self; 6, identifier:results; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, for_statement; 11, expression_statement; 12, for_statement; 13, return_statement; 14, comment:"""
Order the results.
:param results: The disordened results.
:type results: array.bs4.element.Tag
:return: The ordened results.
:rtype: array.bs4.element.Tag
"""; 15, assignment; 16, assignment; 17, identifier:result; 18, identifier:results; 19, block; 20, assignment; 21, identifier:group; 22, identifier:groups; 23, block; 24, identifier:array; 25, identifier:parents; 26, list; 27, identifier:groups; 28, list; 29, if_statement; 30, identifier:array; 31, list; 32, expression_statement; 33, not_operator; 34, block; 35, else_clause; 36, augmented_assignment; 37, call; 38, expression_statement; 39, expression_statement; 40, expression_statement; 41, block; 42, identifier:array; 43, call; 44, attribute; 45, argument_list; 46, call; 47, call; 48, call; 49, expression_statement; 50, identifier:sorted; 51, argument_list; 52, identifier:self; 53, identifier:_in_list; 54, identifier:parents; 55, attribute; 56, attribute; 57, argument_list; 58, attribute; 59, argument_list; 60, attribute; 61, argument_list; 62, call; 63, identifier:group; 64, keyword_argument; 65, identifier:result; 66, identifier:parent; 67, identifier:parents; 68, identifier:append; 69, attribute; 70, identifier:groups; 71, identifier:append; 72, list; 73, subscript; 74, identifier:append; 75, identifier:result; 76, attribute; 77, argument_list; 78, identifier:key; 79, lambda; 80, identifier:result; 81, identifier:parent; 82, identifier:groups; 83, binary_operator:len(groups) - 1; 84, subscript; 85, identifier:append; 86, identifier:result; 87, lambda_parameters; 88, call; 89, call; 90, integer:1; 91, identifier:groups; 92, call; 93, identifier:element; 94, attribute; 95, argument_list; 96, identifier:len; 97, argument_list; 98, attribute; 99, argument_list; 100, attribute; 101, identifier:index; 102, identifier:element; 103, identifier:groups; 104, identifier:parents; 105, identifier:index; 106, attribute; 107, attribute; 108, identifier:contents; 109, identifier:result; 110, identifier:parent; 111, identifier:element; 112, identifier:parent | 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; 12, 23; 13, 24; 15, 25; 15, 26; 16, 27; 16, 28; 19, 29; 20, 30; 20, 31; 23, 32; 29, 33; 29, 34; 29, 35; 32, 36; 33, 37; 34, 38; 34, 39; 34, 40; 35, 41; 36, 42; 36, 43; 37, 44; 37, 45; 38, 46; 39, 47; 40, 48; 41, 49; 43, 50; 43, 51; 44, 52; 44, 53; 45, 54; 45, 55; 46, 56; 46, 57; 47, 58; 47, 59; 48, 60; 48, 61; 49, 62; 51, 63; 51, 64; 55, 65; 55, 66; 56, 67; 56, 68; 57, 69; 58, 70; 58, 71; 59, 72; 60, 73; 60, 74; 61, 75; 62, 76; 62, 77; 64, 78; 64, 79; 69, 80; 69, 81; 73, 82; 73, 83; 76, 84; 76, 85; 77, 86; 79, 87; 79, 88; 83, 89; 83, 90; 84, 91; 84, 92; 87, 93; 88, 94; 88, 95; 89, 96; 89, 97; 92, 98; 92, 99; 94, 100; 94, 101; 95, 102; 97, 103; 98, 104; 98, 105; 99, 106; 100, 107; 100, 108; 106, 109; 106, 110; 107, 111; 107, 112 | def _sort_results(self, results):
"""
Order the results.
:param results: The disordened results.
:type results: array.bs4.element.Tag
:return: The ordened results.
:rtype: array.bs4.element.Tag
"""
parents = []
groups = []
for result in results:
if not self._in_list(parents, result.parent):
parents.append(result.parent)
groups.append([])
groups[len(groups) - 1].append(result)
else:
groups[parents.index(result.parent)].append(result)
array = []
for group in groups:
array += sorted(
group,
key=lambda element: element.parent.contents.index(element)
)
return array |
0, module; 1, function_definition; 2, function_name:_update_sorting; 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, if_statement; 13, expression_statement; 14, expression_statement; 15, comment:""" Insert new entries into the merged iterator.
:param sorted_tops: A SortedDict.
:param tops: The most recent entry from each iterator.
:param idxs: The indices to update.
"""; 16, assignment; 17, assignment; 18, assignment; 19, assignment; 20, identifier:idx; 21, attribute; 22, block; 23, comparison_operator:len(sorted_tops) == 0; 24, block; 25, assignment; 26, assignment; 27, identifier:key; 28, attribute; 29, identifier:sorted_tops; 30, attribute; 31, identifier:tops; 32, attribute; 33, identifier:iterators; 34, attribute; 35, identifier:self; 36, identifier:idxs; 37, try_statement; 38, call; 39, integer:0; 40, raise_statement; 41, pattern_list; 42, call; 43, attribute; 44, integer:0; 45, identifier:self; 46, identifier:key; 47, identifier:self; 48, identifier:sorted_tops; 49, identifier:self; 50, identifier:tops; 51, identifier:self; 52, identifier:iterators; 53, block; 54, except_clause; 55, identifier:len; 56, argument_list; 57, identifier:StopIteration; 58, identifier:key; 59, attribute; 60, attribute; 61, argument_list; 62, identifier:self; 63, identifier:c_idx; 64, expression_statement; 65, expression_statement; 66, if_statement; 67, expression_statement; 68, identifier:StopIteration; 69, block; 70, identifier:sorted_tops; 71, identifier:self; 72, identifier:idxs; 73, identifier:sorted_tops; 74, identifier:popitem; 75, keyword_argument; 76, assignment; 77, assignment; 78, comparison_operator:top_key not in sorted_tops; 79, block; 80, call; 81, pass_statement; 82, identifier:last; 83, False; 84, subscript; 85, call; 86, identifier:top_key; 87, call; 88, identifier:top_key; 89, identifier:sorted_tops; 90, expression_statement; 91, attribute; 92, argument_list; 93, identifier:tops; 94, identifier:idx; 95, identifier:next; 96, argument_list; 97, identifier:key; 98, argument_list; 99, assignment; 100, subscript; 101, identifier:append; 102, identifier:idx; 103, subscript; 104, subscript; 105, subscript; 106, list; 107, identifier:sorted_tops; 108, identifier:top_key; 109, identifier:iterators; 110, identifier:idx; 111, identifier:tops; 112, identifier:idx; 113, identifier:sorted_tops; 114, identifier:top_key | 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; 6, 15; 7, 16; 8, 17; 9, 18; 10, 19; 11, 20; 11, 21; 11, 22; 12, 23; 12, 24; 13, 25; 14, 26; 16, 27; 16, 28; 17, 29; 17, 30; 18, 31; 18, 32; 19, 33; 19, 34; 21, 35; 21, 36; 22, 37; 23, 38; 23, 39; 24, 40; 25, 41; 25, 42; 26, 43; 26, 44; 28, 45; 28, 46; 30, 47; 30, 48; 32, 49; 32, 50; 34, 51; 34, 52; 37, 53; 37, 54; 38, 55; 38, 56; 40, 57; 41, 58; 41, 59; 42, 60; 42, 61; 43, 62; 43, 63; 53, 64; 53, 65; 53, 66; 53, 67; 54, 68; 54, 69; 56, 70; 59, 71; 59, 72; 60, 73; 60, 74; 61, 75; 64, 76; 65, 77; 66, 78; 66, 79; 67, 80; 69, 81; 75, 82; 75, 83; 76, 84; 76, 85; 77, 86; 77, 87; 78, 88; 78, 89; 79, 90; 80, 91; 80, 92; 84, 93; 84, 94; 85, 95; 85, 96; 87, 97; 87, 98; 90, 99; 91, 100; 91, 101; 92, 102; 96, 103; 98, 104; 99, 105; 99, 106; 100, 107; 100, 108; 103, 109; 103, 110; 104, 111; 104, 112; 105, 113; 105, 114 | def _update_sorting(self):
""" Insert new entries into the merged iterator.
:param sorted_tops: A SortedDict.
:param tops: The most recent entry from each iterator.
:param idxs: The indices to update.
"""
key = self.key
sorted_tops = self.sorted_tops
tops = self.tops
iterators = self.iterators
for idx in self.idxs:
try:
tops[idx] = next(iterators[idx])
top_key = key(tops[idx])
if top_key not in sorted_tops:
sorted_tops[top_key] = []
sorted_tops[top_key].append(idx)
except StopIteration:
pass
if len(sorted_tops) == 0:
raise StopIteration
key, self.idxs = sorted_tops.popitem(last=False)
self.c_idx = 0 |
0, module; 1, function_definition; 2, function_name:domain_user_stats; 3, parameters; 4, comment:# type: () -> pd.Series; 5, block; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, comment:""" Get number of distinct email addresses in observed domains
TODO: get up to date with new projects layout
How to build email_domain_users.csv:
from collections import defaultdict
import logging
from common import utils as common
import stscraper as scraper
log = logging.getLogger("domain_user_stats")
stats = defaultdict(set)
for ecosystem in common.ECOSYSTEMS:
urls = common.package_urls(ecosystem)
for package_name, url in urls.items():
log.info(package_name)
try:
cs = scraper.commits(url)
except scraper.RepoDoesNotExist:
continue
for email_addr in cs["author_email"].dropna().unique():
if not email_addr or pd.isnull(email_addr):
continue
try:
user, email_domain = clean(email_addr).split("@")
except InvalidEmail:
continue
stats[email_domain].add(user)
s = pd.Series({dm: len(users) for dm, users in stats.items()})
s = s.rename("users").sort_values(ascending=False)
s.to_csv("common/email_domain_users.csv", encoding="utf8", header=True)
return s
"""; 11, assignment; 12, assignment; 13, subscript; 14, identifier:fname; 15, call; 16, identifier:stats; 17, call; 18, identifier:stats; 19, call; 20, attribute; 21, argument_list; 22, attribute; 23, argument_list; 24, attribute; 25, argument_list; 26, attribute; 27, identifier:join; 28, call; 29, string:"email_domain_users.csv"; 30, identifier:pd; 31, identifier:read_csv; 32, identifier:fname; 33, keyword_argument; 34, keyword_argument; 35, keyword_argument; 36, identifier:pd; 37, identifier:notnull; 38, attribute; 39, identifier:os; 40, identifier:path; 41, attribute; 42, argument_list; 43, identifier:header; 44, integer:0; 45, identifier:squeeze; 46, True; 47, identifier:index_col; 48, integer:0; 49, identifier:stats; 50, identifier:index; 51, attribute; 52, identifier:dirname; 53, identifier:__file__; 54, identifier:os; 55, identifier:path | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 5, 6; 5, 7; 5, 8; 5, 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; 19, 24; 19, 25; 20, 26; 20, 27; 21, 28; 21, 29; 22, 30; 22, 31; 23, 32; 23, 33; 23, 34; 23, 35; 24, 36; 24, 37; 25, 38; 26, 39; 26, 40; 28, 41; 28, 42; 33, 43; 33, 44; 34, 45; 34, 46; 35, 47; 35, 48; 38, 49; 38, 50; 41, 51; 41, 52; 42, 53; 51, 54; 51, 55 | def domain_user_stats():
# type: () -> pd.Series
""" Get number of distinct email addresses in observed domains
TODO: get up to date with new projects layout
How to build email_domain_users.csv:
from collections import defaultdict
import logging
from common import utils as common
import stscraper as scraper
log = logging.getLogger("domain_user_stats")
stats = defaultdict(set)
for ecosystem in common.ECOSYSTEMS:
urls = common.package_urls(ecosystem)
for package_name, url in urls.items():
log.info(package_name)
try:
cs = scraper.commits(url)
except scraper.RepoDoesNotExist:
continue
for email_addr in cs["author_email"].dropna().unique():
if not email_addr or pd.isnull(email_addr):
continue
try:
user, email_domain = clean(email_addr).split("@")
except InvalidEmail:
continue
stats[email_domain].add(user)
s = pd.Series({dm: len(users) for dm, users in stats.items()})
s = s.rename("users").sort_values(ascending=False)
s.to_csv("common/email_domain_users.csv", encoding="utf8", header=True)
return s
"""
fname = os.path.join(os.path.dirname(__file__), "email_domain_users.csv")
stats = pd.read_csv(fname, header=0, squeeze=True, index_col=0)
return stats[pd.notnull(stats.index)] |
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, expression_statement; 10, function_definition; 11, comment:# node is initially weighted with the number of immediate dependencies; 12, for_statement; 13, comment:# Start with a list of nodes who have no dependents; 14, expression_statement; 15, while_statement; 16, expression_statement; 17, expression_statement; 18, comment:"""
Kahn's algorithm for Topological Sorting
- Finds cycles in graph
- Computes dependency weight
"""; 19, assignment; 20, assignment; 21, assignment; 22, function_name:get_pointers_for_edge_nodes; 23, parameters; 24, block; 25, identifier:node; 26, identifier:nodes; 27, block; 28, assignment; 29, identifier:resolved; 30, block; 31, assignment; 32, assignment; 33, identifier:sorted_graph; 34, list; 35, identifier:node_map; 36, call; 37, identifier:nodes; 38, list_comprehension; 39, identifier:visitor_decorated_node; 40, expression_statement; 41, expression_statement; 42, for_statement; 43, return_statement; 44, for_statement; 45, identifier:resolved; 46, list_comprehension; 47, expression_statement; 48, expression_statement; 49, for_statement; 50, attribute; 51, list_comprehension; 52, attribute; 53, call; 54, attribute; 55, argument_list; 56, call; 57, for_in_clause; 58, assignment; 59, assignment; 60, identifier:node; 61, identifier:nodes; 62, block; 63, identifier:edges; 64, identifier:edge; 65, call; 66, block; 67, identifier:node; 68, for_in_clause; 69, if_clause; 70, assignment; 71, call; 72, identifier:edge; 73, call; 74, block; 75, identifier:self; 76, identifier:_circular_dependencies; 77, call; 78, for_in_clause; 79, if_clause; 80, identifier:self; 81, identifier:_sorted_nodes; 82, identifier:list; 83, argument_list; 84, attribute; 85, identifier:get_nodes; 86, identifier:NodeVisitor; 87, argument_list; 88, identifier:node; 89, identifier:node_map; 90, identifier:edges; 91, list; 92, identifier:edge_ids; 93, call; 94, if_statement; 95, identifier:get_pointers_for_edge_nodes; 96, argument_list; 97, expression_statement; 98, identifier:node; 99, identifier:nodes; 100, comparison_operator:node.get_weight() == 0; 101, identifier:node; 102, call; 103, attribute; 104, argument_list; 105, identifier:get_pointers_for_edge_nodes; 106, argument_list; 107, expression_statement; 108, if_statement; 109, attribute; 110, argument_list; 111, identifier:node; 112, identifier:nodes; 113, comparison_operator:node.get_weight() > 0; 114, call; 115, identifier:self; 116, identifier:_graph; 117, subscript; 118, attribute; 119, argument_list; 120, comparison_operator:node.get_id() in edge_ids; 121, block; 122, identifier:node; 123, call; 124, call; 125, integer:0; 126, attribute; 127, argument_list; 128, identifier:sorted_graph; 129, identifier:append; 130, identifier:node; 131, identifier:node; 132, call; 133, comparison_operator:edge.get_weight() == 0; 134, block; 135, identifier:node; 136, identifier:get_node; 137, call; 138, integer:0; 139, identifier:reversed; 140, argument_list; 141, identifier:node_map; 142, identifier:node; 143, call; 144, identifier:get_edges; 145, call; 146, identifier:edge_ids; 147, expression_statement; 148, attribute; 149, argument_list; 150, attribute; 151, argument_list; 152, identifier:resolved; 153, identifier:pop; 154, attribute; 155, argument_list; 156, call; 157, integer:0; 158, expression_statement; 159, attribute; 160, argument_list; 161, list_comprehension; 162, attribute; 163, argument_list; 164, attribute; 165, argument_list; 166, call; 167, identifier:edge; 168, identifier:increment; 169, identifier:node; 170, identifier:get_weight; 171, identifier:edge; 172, identifier:decrement; 173, attribute; 174, argument_list; 175, call; 176, identifier:node; 177, identifier:get_weight; 178, call; 179, for_in_clause; 180, identifier:visitor_decorated_node; 181, identifier:get_node; 182, identifier:node; 183, identifier:get_id; 184, attribute; 185, argument_list; 186, identifier:edge; 187, identifier:get_weight; 188, attribute; 189, argument_list; 190, attribute; 191, argument_list; 192, identifier:node; 193, identifier:sorted_graph; 194, identifier:edges; 195, identifier:append; 196, identifier:node; 197, identifier:resolved; 198, identifier:append; 199, identifier:edge; 200, identifier:node; 201, identifier:get_node | 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; 4, 16; 4, 17; 6, 18; 7, 19; 8, 20; 9, 21; 10, 22; 10, 23; 10, 24; 12, 25; 12, 26; 12, 27; 14, 28; 15, 29; 15, 30; 16, 31; 17, 32; 19, 33; 19, 34; 20, 35; 20, 36; 21, 37; 21, 38; 23, 39; 24, 40; 24, 41; 24, 42; 24, 43; 27, 44; 28, 45; 28, 46; 30, 47; 30, 48; 30, 49; 31, 50; 31, 51; 32, 52; 32, 53; 36, 54; 36, 55; 38, 56; 38, 57; 40, 58; 41, 59; 42, 60; 42, 61; 42, 62; 43, 63; 44, 64; 44, 65; 44, 66; 46, 67; 46, 68; 46, 69; 47, 70; 48, 71; 49, 72; 49, 73; 49, 74; 50, 75; 50, 76; 51, 77; 51, 78; 51, 79; 52, 80; 52, 81; 53, 82; 53, 83; 54, 84; 54, 85; 56, 86; 56, 87; 57, 88; 57, 89; 58, 90; 58, 91; 59, 92; 59, 93; 62, 94; 65, 95; 65, 96; 66, 97; 68, 98; 68, 99; 69, 100; 70, 101; 70, 102; 71, 103; 71, 104; 73, 105; 73, 106; 74, 107; 74, 108; 77, 109; 77, 110; 78, 111; 78, 112; 79, 113; 83, 114; 84, 115; 84, 116; 87, 117; 93, 118; 93, 119; 94, 120; 94, 121; 96, 122; 97, 123; 100, 124; 100, 125; 102, 126; 102, 127; 103, 128; 103, 129; 104, 130; 106, 131; 107, 132; 108, 133; 108, 134; 109, 135; 109, 136; 113, 137; 113, 138; 114, 139; 114, 140; 117, 141; 117, 142; 118, 143; 118, 144; 120, 145; 120, 146; 121, 147; 123, 148; 123, 149; 124, 150; 124, 151; 126, 152; 126, 153; 132, 154; 132, 155; 133, 156; 133, 157; 134, 158; 137, 159; 137, 160; 140, 161; 143, 162; 143, 163; 145, 164; 145, 165; 147, 166; 148, 167; 148, 168; 150, 169; 150, 170; 154, 171; 154, 172; 156, 173; 156, 174; 158, 175; 159, 176; 159, 177; 161, 178; 161, 179; 162, 180; 162, 181; 164, 182; 164, 183; 166, 184; 166, 185; 173, 186; 173, 187; 175, 188; 175, 189; 178, 190; 178, 191; 179, 192; 179, 193; 184, 194; 184, 195; 185, 196; 188, 197; 188, 198; 189, 199; 190, 200; 190, 201 | def _topological_sort(self):
"""
Kahn's algorithm for Topological Sorting
- Finds cycles in graph
- Computes dependency weight
"""
sorted_graph = []
node_map = self._graph.get_nodes()
nodes = [NodeVisitor(node_map[node]) for node in node_map]
def get_pointers_for_edge_nodes(visitor_decorated_node):
edges = []
edge_ids = visitor_decorated_node.get_node().get_edges()
for node in nodes:
if node.get_id() in edge_ids:
edges.append(node)
return edges
# node is initially weighted with the number of immediate dependencies
for node in nodes:
for edge in get_pointers_for_edge_nodes(node):
edge.increment()
# Start with a list of nodes who have no dependents
resolved = [node for node in nodes if node.get_weight() == 0]
while resolved:
node = resolved.pop()
sorted_graph.append(node)
for edge in get_pointers_for_edge_nodes(node):
edge.decrement()
if edge.get_weight() == 0:
resolved.append(edge)
self._circular_dependencies = [
node.get_node() for node in nodes if node.get_weight() > 0]
self._sorted_nodes = list(reversed(
[node.get_node() for node in sorted_graph])) |
0, module; 1, function_definition; 2, function_name:plugins; 3, parameters; 4, comment:# TODO: share this documentation with `../doc/plugin.rst`...; 5, block; 6, identifier:group; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, identifier:spec; 14, None; 15, string:'''
Returns a `PluginSet` object for the specified setuptools-style
entrypoint `group`. This is just a wrapper around
`pkg_resources.iter_entry_points` that allows the plugins to sort
and override themselves.
The optional `spec` parameter controls how and what plugins are
loaded. If it is ``None`` or the special value ``'*'``, then the
normal plugin loading will occur, i.e. all registered plugins will
be loaded and their self-declared ordering and dependencies will be
applied.
Otherwise, the `spec` is taken as a comma- or whitespace-separated
list of plugins to load. In this mode, the `spec` can either specify
an exact list of plugins to load, in the specified order, referred
to as an "absolute" spec. Otherwise, it is a "relative" spec, which
indicates that it only adjusts the standard registered plugin
loading. A spec is a list of either absolute or relative
instructions, and they cannot be mixed.
In either mode, a plugin is identified either by name for registered
plugins (e.g. ``foo``), or by fully-qualified Python module and
symbol name for unregistered plugins
(e.g. ``package.module.symbol``).
Plugins in an absolute spec are loaded in the order specified and
can be optionally prefixed with the following special characters:
* ``'?'`` : the specified plugin should be loaded if available. If
it is not registered, cannot be found, or cannot be loaded, then
it is ignored (a DEBUG log message will be emitted, however).
Plugins in a relative spec are always prefixed with at least one of
the following special characters:
* ``'-'`` : removes the specified plugin; this does not affect
plugin ordering, it only removes the plugin from the loaded
list. If the plugin does not exist, no error is thrown.
* ``'+'`` : adds or requires the specified plugin to the loaded
set. If the plugin is not a named/registered plugin, then it will
be loaded as an asset-symbol, i.e. a Python-dotted module and
symbol name. If the plugin does not exist or cannot be loaded,
this will throw an error. It does not affect the plugin ordering
of registered plugins.
* ``'/'`` : the plugin name is taken as a regular expression that
will be used to match plugin names and it must terminate in a
slash. Note that this must be the **last** element in the spec
list.
Examples:
* ``'*'`` : load all registered plugins.
* ``'foo,bar'`` : load the "foo" plugin, then the "bar" plugin.
* ``'foo,?bar'`` : load the "foo" plugin and if the "bar" plugin
exists, load it too.
* ``'-zig'`` : load all registered plugins except the "zig" plugin.
* ``'+pkg.foo.bar'`` : load all registered plugins and then load
the "pkg.foo.bar" Python symbol.
* ``'pkg.foo.bar'`` : load only the "pkg.foo.bar" Python symbol.
'''; 16, assignment; 17, assignment; 18, augmented_assignment; 19, call; 20, identifier:pspec; 21, call; 22, identifier:plugs; 23, call; 24, identifier:plugs; 25, call; 26, identifier:PluginSet; 27, argument_list; 28, identifier:_parse_spec; 29, argument_list; 30, identifier:list; 31, argument_list; 32, identifier:list; 33, argument_list; 34, identifier:group; 35, identifier:spec; 36, call; 37, identifier:spec; 38, call; 39, call; 40, identifier:list; 41, argument_list; 42, identifier:_get_registered_plugins; 43, argument_list; 44, identifier:_get_unregistered_plugins; 45, argument_list; 46, call; 47, identifier:group; 48, identifier:pspec; 49, identifier:group; 50, identifier:plugs; 51, identifier:pspec; 52, identifier:_sort_plugins; 53, argument_list; 54, identifier:group; 55, identifier:plugs; 56, identifier:pspec; 57, identifier:spec | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 3, 7; 5, 8; 5, 9; 5, 10; 5, 11; 5, 12; 7, 13; 7, 14; 8, 15; 9, 16; 10, 17; 11, 18; 12, 19; 16, 20; 16, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 19, 27; 21, 28; 21, 29; 23, 30; 23, 31; 25, 32; 25, 33; 27, 34; 27, 35; 27, 36; 29, 37; 31, 38; 33, 39; 36, 40; 36, 41; 38, 42; 38, 43; 39, 44; 39, 45; 41, 46; 43, 47; 43, 48; 45, 49; 45, 50; 45, 51; 46, 52; 46, 53; 53, 54; 53, 55; 53, 56; 53, 57 | def plugins(group, spec=None):
# TODO: share this documentation with `../doc/plugin.rst`...
'''
Returns a `PluginSet` object for the specified setuptools-style
entrypoint `group`. This is just a wrapper around
`pkg_resources.iter_entry_points` that allows the plugins to sort
and override themselves.
The optional `spec` parameter controls how and what plugins are
loaded. If it is ``None`` or the special value ``'*'``, then the
normal plugin loading will occur, i.e. all registered plugins will
be loaded and their self-declared ordering and dependencies will be
applied.
Otherwise, the `spec` is taken as a comma- or whitespace-separated
list of plugins to load. In this mode, the `spec` can either specify
an exact list of plugins to load, in the specified order, referred
to as an "absolute" spec. Otherwise, it is a "relative" spec, which
indicates that it only adjusts the standard registered plugin
loading. A spec is a list of either absolute or relative
instructions, and they cannot be mixed.
In either mode, a plugin is identified either by name for registered
plugins (e.g. ``foo``), or by fully-qualified Python module and
symbol name for unregistered plugins
(e.g. ``package.module.symbol``).
Plugins in an absolute spec are loaded in the order specified and
can be optionally prefixed with the following special characters:
* ``'?'`` : the specified plugin should be loaded if available. If
it is not registered, cannot be found, or cannot be loaded, then
it is ignored (a DEBUG log message will be emitted, however).
Plugins in a relative spec are always prefixed with at least one of
the following special characters:
* ``'-'`` : removes the specified plugin; this does not affect
plugin ordering, it only removes the plugin from the loaded
list. If the plugin does not exist, no error is thrown.
* ``'+'`` : adds or requires the specified plugin to the loaded
set. If the plugin is not a named/registered plugin, then it will
be loaded as an asset-symbol, i.e. a Python-dotted module and
symbol name. If the plugin does not exist or cannot be loaded,
this will throw an error. It does not affect the plugin ordering
of registered plugins.
* ``'/'`` : the plugin name is taken as a regular expression that
will be used to match plugin names and it must terminate in a
slash. Note that this must be the **last** element in the spec
list.
Examples:
* ``'*'`` : load all registered plugins.
* ``'foo,bar'`` : load the "foo" plugin, then the "bar" plugin.
* ``'foo,?bar'`` : load the "foo" plugin and if the "bar" plugin
exists, load it too.
* ``'-zig'`` : load all registered plugins except the "zig" plugin.
* ``'+pkg.foo.bar'`` : load all registered plugins and then load
the "pkg.foo.bar" Python symbol.
* ``'pkg.foo.bar'`` : load only the "pkg.foo.bar" Python symbol.
'''
pspec = _parse_spec(spec)
plugs = list(_get_registered_plugins(group, pspec))
plugs += list(_get_unregistered_plugins(group, plugs, pspec))
return PluginSet(group, spec, list(_sort_plugins(group, plugs, pspec, spec))) |
0, module; 1, function_definition; 2, function_name:match_any_string; 3, parameters; 4, block; 5, identifier:self; 6, identifier:strings; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, for_statement; 15, return_statement; 16, identifier:word; 17, integer:0; 18, identifier:offset; 19, integer:0; 20, comment:"""Attempts to match each string in strings in order.
Will return the string that matches or an empty string if no match.
If word arg >= 1 then only match if string is followed by a whitespace
which is much higher performance.
If word is 0 then you should sort the strings argument yourself by
length.
"""; 21, identifier:word; 22, block; 23, assignment; 24, assignment; 25, assignment; 26, identifier:string; 27, identifier:strings; 28, block; 29, string; 30, expression_statement; 31, return_statement; 32, identifier:current; 33, string; 34, identifier:currentlength; 35, integer:0; 36, identifier:length; 37, integer:0; 38, expression_statement; 39, if_statement; 40, if_statement; 41, assignment; 42, conditional_expression:current if current in strings else ''; 43, assignment; 44, comparison_operator:length != currentlength; 45, block; 46, comparison_operator:string == current; 47, block; 48, identifier:current; 49, call; 50, identifier:current; 51, comparison_operator:current in strings; 52, string; 53, identifier:length; 54, call; 55, identifier:length; 56, identifier:currentlength; 57, expression_statement; 58, identifier:string; 59, identifier:current; 60, return_statement; 61, attribute; 62, argument_list; 63, identifier:current; 64, identifier:strings; 65, identifier:len; 66, argument_list; 67, assignment; 68, identifier:string; 69, identifier:self; 70, identifier:get_string; 71, identifier:offset; 72, identifier:string; 73, identifier:current; 74, call; 75, attribute; 76, argument_list; 77, identifier:self; 78, identifier:get_length; 79, identifier:length; 80, identifier:offset | 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; 12, 24; 13, 25; 14, 26; 14, 27; 14, 28; 15, 29; 22, 30; 22, 31; 23, 32; 23, 33; 24, 34; 24, 35; 25, 36; 25, 37; 28, 38; 28, 39; 28, 40; 30, 41; 31, 42; 38, 43; 39, 44; 39, 45; 40, 46; 40, 47; 41, 48; 41, 49; 42, 50; 42, 51; 42, 52; 43, 53; 43, 54; 44, 55; 44, 56; 45, 57; 46, 58; 46, 59; 47, 60; 49, 61; 49, 62; 51, 63; 51, 64; 54, 65; 54, 66; 57, 67; 60, 68; 61, 69; 61, 70; 62, 71; 66, 72; 67, 73; 67, 74; 74, 75; 74, 76; 75, 77; 75, 78; 76, 79; 76, 80 | def match_any_string(self, strings, word=0, offset=0):
"""Attempts to match each string in strings in order.
Will return the string that matches or an empty string if no match.
If word arg >= 1 then only match if string is followed by a whitespace
which is much higher performance.
If word is 0 then you should sort the strings argument yourself by
length.
"""
if word:
current = self.get_string(offset)
return current if current in strings else ''
current = ''
currentlength = 0
length = 0
for string in strings:
length = len(string)
if length != currentlength:
current = self.get_length(length, offset)
if string == current:
return string
return '' |
0, module; 1, function_definition; 2, function_name:decide_which_users_to_annotate; 3, parameters; 4, block; 5, identifier:centrality_vector; 6, identifier:number_to_annotate; 7, identifier:already_annotated; 8, identifier:node_to_id; 9, expression_statement; 10, comment:# Sort the centrality vector according to decreasing centrality.; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, comment:# Get the sublist of Twitter user ids to return.; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, for_statement; 19, return_statement; 20, comment:"""
Sorts a centrality vector and returns the Twitter user ids that are to be annotated.
Inputs: - centrality_vector: A numpy array vector, that contains the centrality values for all users.
- number_to_annotate: The number of users to annotate.
- already_annotated: A python set of user twitter ids that have already been annotated.
- node_to_id: A python dictionary that maps graph nodes to user twitter ids.
Output: - user_id_list: A python list of Twitter user ids.
"""; 21, assignment; 22, assignment; 23, comparison_operator:centrality_vector.size > 1; 24, block; 25, else_clause; 26, assignment; 27, assignment; 28, assignment; 29, identifier:node; 30, identifier:reversed_ind; 31, block; 32, identifier:user_id_list; 33, identifier:centrality_vector; 34, call; 35, identifier:ind; 36, call; 37, attribute; 38, integer:1; 39, expression_statement; 40, block; 41, identifier:user_id_list; 42, call; 43, identifier:append_user_id; 44, attribute; 45, identifier:counter; 46, integer:0; 47, expression_statement; 48, if_statement; 49, attribute; 50, argument_list; 51, attribute; 52, argument_list; 53, identifier:centrality_vector; 54, identifier:size; 55, assignment; 56, expression_statement; 57, expression_statement; 58, identifier:list; 59, argument_list; 60, identifier:user_id_list; 61, identifier:append; 62, assignment; 63, comparison_operator:user_twitter_id not in already_annotated; 64, block; 65, identifier:np; 66, identifier:asarray; 67, identifier:centrality_vector; 68, identifier:np; 69, identifier:argsort; 70, call; 71, identifier:reversed_ind; 72, subscript; 73, assignment; 74, assignment; 75, identifier:user_twitter_id; 76, subscript; 77, identifier:user_twitter_id; 78, identifier:already_annotated; 79, expression_statement; 80, expression_statement; 81, if_statement; 82, attribute; 83, argument_list; 84, identifier:ind; 85, slice; 86, identifier:reversed_ind; 87, call; 88, identifier:reversed_ind; 89, call; 90, identifier:node_to_id; 91, identifier:node; 92, call; 93, augmented_assignment; 94, comparison_operator:counter >= number_to_annotate; 95, block; 96, identifier:np; 97, identifier:squeeze; 98, identifier:centrality_vector; 99, unary_operator; 100, identifier:list; 101, argument_list; 102, attribute; 103, argument_list; 104, identifier:append_user_id; 105, argument_list; 106, identifier:counter; 107, integer:1; 108, identifier:counter; 109, identifier:number_to_annotate; 110, break_statement; 111, integer:1; 112, identifier:reversed_ind; 113, identifier:append; 114, identifier:ind; 115, identifier:user_twitter_id | 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; 9, 20; 11, 21; 12, 22; 13, 23; 13, 24; 13, 25; 15, 26; 16, 27; 17, 28; 18, 29; 18, 30; 18, 31; 19, 32; 21, 33; 21, 34; 22, 35; 22, 36; 23, 37; 23, 38; 24, 39; 25, 40; 26, 41; 26, 42; 27, 43; 27, 44; 28, 45; 28, 46; 31, 47; 31, 48; 34, 49; 34, 50; 36, 51; 36, 52; 37, 53; 37, 54; 39, 55; 40, 56; 40, 57; 42, 58; 42, 59; 44, 60; 44, 61; 47, 62; 48, 63; 48, 64; 49, 65; 49, 66; 50, 67; 51, 68; 51, 69; 52, 70; 55, 71; 55, 72; 56, 73; 57, 74; 62, 75; 62, 76; 63, 77; 63, 78; 64, 79; 64, 80; 64, 81; 70, 82; 70, 83; 72, 84; 72, 85; 73, 86; 73, 87; 74, 88; 74, 89; 76, 90; 76, 91; 79, 92; 80, 93; 81, 94; 81, 95; 82, 96; 82, 97; 83, 98; 85, 99; 87, 100; 87, 101; 89, 102; 89, 103; 92, 104; 92, 105; 93, 106; 93, 107; 94, 108; 94, 109; 95, 110; 99, 111; 102, 112; 102, 113; 103, 114; 105, 115 | def decide_which_users_to_annotate(centrality_vector,
number_to_annotate,
already_annotated,
node_to_id):
"""
Sorts a centrality vector and returns the Twitter user ids that are to be annotated.
Inputs: - centrality_vector: A numpy array vector, that contains the centrality values for all users.
- number_to_annotate: The number of users to annotate.
- already_annotated: A python set of user twitter ids that have already been annotated.
- node_to_id: A python dictionary that maps graph nodes to user twitter ids.
Output: - user_id_list: A python list of Twitter user ids.
"""
# Sort the centrality vector according to decreasing centrality.
centrality_vector = np.asarray(centrality_vector)
ind = np.argsort(np.squeeze(centrality_vector))
if centrality_vector.size > 1:
reversed_ind = ind[::-1]
else:
reversed_ind = list()
reversed_ind = reversed_ind.append(ind)
# Get the sublist of Twitter user ids to return.
user_id_list = list()
append_user_id = user_id_list.append
counter = 0
for node in reversed_ind:
user_twitter_id = node_to_id[node]
if user_twitter_id not in already_annotated:
append_user_id(user_twitter_id)
counter += 1
if counter >= number_to_annotate:
break
return user_id_list |
0, module; 1, function_definition; 2, function_name:search; 3, parameters; 4, block; 5, identifier:self; 6, identifier:query; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, return_statement; 17, identifier:sort_map; 18, dictionary; 19, identifier:strict_sort; 20, False; 21, string; 22, assignment; 23, identifier:strict_sort; 24, block; 25, assignment; 26, assignment; 27, assignment; 28, assignment; 29, identifier:items; 30, pair; 31, pair; 32, pair; 33, pair; 34, pair; 35, string_content:Sends a search request to emby, returns results
|coro|
Parameters
----------
query : str
the search string to send to emby
sort_map : dict
is a dict of strings to ints. Strings should be item types, and
the ints are the priority of those types(for sorting).
lower valued(0) will appear first.
strict_sort : bool
if True, then only item types in the keys of sortmap will be
included in the results
Returns
-------
list
list of emby objects; 36, identifier:search_params; 37, dictionary; 38, expression_statement; 39, identifier:json; 40, await; 41, identifier:items; 42, await; 43, identifier:m_size; 44, call; 45, identifier:items; 46, call; 47, string; 48, integer:0; 49, string; 50, integer:1; 51, string; 52, integer:2; 53, string; 54, integer:3; 55, string; 56, integer:4; 57, pair; 58, pair; 59, assignment; 60, call; 61, call; 62, identifier:len; 63, argument_list; 64, identifier:sorted; 65, argument_list; 66, string_content:BoxSet; 67, string_content:Series; 68, string_content:Movie; 69, string_content:Audio; 70, string_content:Person; 71, string; 72, False; 73, string; 74, identifier:query; 75, subscript; 76, call; 77, attribute; 78, argument_list; 79, attribute; 80, argument_list; 81, identifier:sort_map; 82, identifier:items; 83, keyword_argument; 84, string_content:remote; 85, string_content:searchTerm; 86, identifier:search_params; 87, string; 88, attribute; 89, argument_list; 90, attribute; 91, identifier:getJson; 92, string; 93, dictionary_splat; 94, identifier:self; 95, identifier:process; 96, subscript; 97, identifier:key; 98, lambda; 99, string_content:IncludeItemTypes; 100, string; 101, identifier:join; 102, call; 103, identifier:self; 104, identifier:connector; 105, string_content:/Search/Hints/; 106, identifier:search_params; 107, identifier:json; 108, string:"SearchHints"; 109, lambda_parameters; 110, call; 111, string_content:,; 112, attribute; 113, argument_list; 114, identifier:x; 115, attribute; 116, argument_list; 117, identifier:sort_map; 118, identifier:keys; 119, identifier:sort_map; 120, identifier:get; 121, attribute; 122, identifier:m_size; 123, identifier:x; 124, identifier:type | 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; 7, 17; 7, 18; 8, 19; 8, 20; 9, 21; 10, 22; 11, 23; 11, 24; 12, 25; 13, 26; 14, 27; 15, 28; 16, 29; 18, 30; 18, 31; 18, 32; 18, 33; 18, 34; 21, 35; 22, 36; 22, 37; 24, 38; 25, 39; 25, 40; 26, 41; 26, 42; 27, 43; 27, 44; 28, 45; 28, 46; 30, 47; 30, 48; 31, 49; 31, 50; 32, 51; 32, 52; 33, 53; 33, 54; 34, 55; 34, 56; 37, 57; 37, 58; 38, 59; 40, 60; 42, 61; 44, 62; 44, 63; 46, 64; 46, 65; 47, 66; 49, 67; 51, 68; 53, 69; 55, 70; 57, 71; 57, 72; 58, 73; 58, 74; 59, 75; 59, 76; 60, 77; 60, 78; 61, 79; 61, 80; 63, 81; 65, 82; 65, 83; 71, 84; 73, 85; 75, 86; 75, 87; 76, 88; 76, 89; 77, 90; 77, 91; 78, 92; 78, 93; 79, 94; 79, 95; 80, 96; 83, 97; 83, 98; 87, 99; 88, 100; 88, 101; 89, 102; 90, 103; 90, 104; 92, 105; 93, 106; 96, 107; 96, 108; 98, 109; 98, 110; 100, 111; 102, 112; 102, 113; 109, 114; 110, 115; 110, 116; 112, 117; 112, 118; 115, 119; 115, 120; 116, 121; 116, 122; 121, 123; 121, 124 | async def search(self, query,
sort_map = {'BoxSet':0,'Series':1,'Movie':2,'Audio':3,'Person':4},
strict_sort = False):
'''Sends a search request to emby, returns results
|coro|
Parameters
----------
query : str
the search string to send to emby
sort_map : dict
is a dict of strings to ints. Strings should be item types, and
the ints are the priority of those types(for sorting).
lower valued(0) will appear first.
strict_sort : bool
if True, then only item types in the keys of sortmap will be
included in the results
Returns
-------
list
list of emby objects
'''
search_params = {
'remote' : False,
'searchTerm' : query
}
if strict_sort:
search_params['IncludeItemTypes'] = ','.join(sort_map.keys())
json = await self.connector.getJson('/Search/Hints/', **search_params)
items = await self.process(json["SearchHints"])
m_size = len(sort_map)
items = sorted(items, key = lambda x : sort_map.get(x.type, m_size))
return items |
0, module; 1, function_definition; 2, function_name:set_attribute_string; 3, parameters; 4, block; 5, identifier:target; 6, identifier:name; 7, identifier:value; 8, expression_statement; 9, expression_statement; 10, comment:""" Sets an attribute to a string on a Dataset or Group.
If the attribute `name` doesn't exist yet, it is created. If it
already exists, it is overwritten if it differs from `value`.
Notes
-----
``set_attributes_all`` is the fastest way to set and delete
Attributes in bulk.
Parameters
----------
target : Dataset or Group
Dataset or Group to set the string attribute of.
name : str
Name of the attribute to set.
value : string
Value to set the attribute to. Can be any sort of string type
that will convert to a ``numpy.bytes_``
See Also
--------
set_attributes_all
"""; 11, call; 12, identifier:set_attribute; 13, argument_list; 14, identifier:target; 15, identifier:name; 16, call; 17, attribute; 18, argument_list; 19, identifier:np; 20, identifier:bytes_; 21, identifier:value | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 8, 10; 9, 11; 11, 12; 11, 13; 13, 14; 13, 15; 13, 16; 16, 17; 16, 18; 17, 19; 17, 20; 18, 21 | def set_attribute_string(target, name, value):
""" Sets an attribute to a string on a Dataset or Group.
If the attribute `name` doesn't exist yet, it is created. If it
already exists, it is overwritten if it differs from `value`.
Notes
-----
``set_attributes_all`` is the fastest way to set and delete
Attributes in bulk.
Parameters
----------
target : Dataset or Group
Dataset or Group to set the string attribute of.
name : str
Name of the attribute to set.
value : string
Value to set the attribute to. Can be any sort of string type
that will convert to a ``numpy.bytes_``
See Also
--------
set_attributes_all
"""
set_attribute(target, name, np.bytes_(value)) |
0, module; 1, function_definition; 2, function_name:__calculate_edge_weights; 3, parameters; 4, block; 5, identifier:dfs_data; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""Calculates the weight of each edge, for embedding-order sorting."""; 12, assignment; 13, assignment; 14, identifier:edge_id; 15, call; 16, block; 17, identifier:weights; 18, identifier:graph; 19, subscript; 20, identifier:weights; 21, dictionary; 22, attribute; 23, argument_list; 24, expression_statement; 25, expression_statement; 26, identifier:dfs_data; 27, string; 28, identifier:graph; 29, identifier:get_all_edge_ids; 30, assignment; 31, assignment; 32, string_content:graph; 33, identifier:edge_weight; 34, call; 35, subscript; 36, identifier:edge_weight; 37, identifier:__edge_weight; 38, argument_list; 39, identifier:weights; 40, identifier:edge_id; 41, identifier:edge_id; 42, identifier:dfs_data | 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; 9, 16; 10, 17; 12, 18; 12, 19; 13, 20; 13, 21; 15, 22; 15, 23; 16, 24; 16, 25; 19, 26; 19, 27; 22, 28; 22, 29; 24, 30; 25, 31; 27, 32; 30, 33; 30, 34; 31, 35; 31, 36; 34, 37; 34, 38; 35, 39; 35, 40; 38, 41; 38, 42 | def __calculate_edge_weights(dfs_data):
"""Calculates the weight of each edge, for embedding-order sorting."""
graph = dfs_data['graph']
weights = {}
for edge_id in graph.get_all_edge_ids():
edge_weight = __edge_weight(edge_id, dfs_data)
weights[edge_id] = edge_weight
return weights |
0, module; 1, function_definition; 2, function_name:__sort_adjacency_lists; 3, parameters; 4, block; 5, identifier:dfs_data; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, return_statement; 13, comment:"""Sorts the adjacency list representation by the edge weights."""; 14, assignment; 15, assignment; 16, assignment; 17, assignment; 18, pattern_list; 19, call; 20, block; 21, identifier:new_adjacency_lists; 22, identifier:new_adjacency_lists; 23, dictionary; 24, identifier:adjacency_lists; 25, subscript; 26, identifier:edge_weights; 27, subscript; 28, identifier:edge_lookup; 29, subscript; 30, identifier:node_id; 31, identifier:adj_list; 32, identifier:list; 33, argument_list; 34, expression_statement; 35, expression_statement; 36, for_statement; 37, comment:# Fronds should be before branches if the weights are equal; 38, expression_statement; 39, comment:# Sort by weights; 40, expression_statement; 41, comment:# Add the new sorted list to the new adjacency list lookup table; 42, expression_statement; 43, identifier:dfs_data; 44, string; 45, identifier:dfs_data; 46, string; 47, identifier:dfs_data; 48, string; 49, call; 50, assignment; 51, assignment; 52, identifier:node_b; 53, identifier:adj_list; 54, block; 55, assignment; 56, call; 57, assignment; 58, string_content:adj; 59, string_content:edge_weights; 60, string_content:edge_lookup; 61, attribute; 62, argument_list; 63, identifier:node_weight_lookup; 64, dictionary; 65, identifier:frond_lookup; 66, dictionary; 67, expression_statement; 68, expression_statement; 69, expression_statement; 70, identifier:new_list; 71, call; 72, attribute; 73, argument_list; 74, subscript; 75, identifier:new_list; 76, identifier:adjacency_lists; 77, identifier:items; 78, assignment; 79, assignment; 80, assignment; 81, identifier:sorted; 82, argument_list; 83, identifier:new_list; 84, identifier:sort; 85, keyword_argument; 86, identifier:new_adjacency_lists; 87, identifier:node_id; 88, identifier:edge_id; 89, call; 90, subscript; 91, subscript; 92, subscript; 93, conditional_expression:1 if edge_lookup[edge_id] == 'backedge' else 2; 94, identifier:adj_list; 95, keyword_argument; 96, identifier:key; 97, lambda; 98, attribute; 99, argument_list; 100, identifier:node_weight_lookup; 101, identifier:node_b; 102, identifier:edge_weights; 103, identifier:edge_id; 104, identifier:frond_lookup; 105, identifier:node_b; 106, integer:1; 107, comparison_operator:edge_lookup[edge_id] == 'backedge'; 108, integer:2; 109, identifier:key; 110, lambda; 111, lambda_parameters; 112, subscript; 113, subscript; 114, identifier:get_first_edge_id_by_node_ids; 115, identifier:node_id; 116, identifier:node_b; 117, subscript; 118, string; 119, lambda_parameters; 120, subscript; 121, identifier:n; 122, identifier:node_weight_lookup; 123, identifier:n; 124, identifier:dfs_data; 125, string; 126, identifier:edge_lookup; 127, identifier:edge_id; 128, string_content:backedge; 129, identifier:n; 130, identifier:frond_lookup; 131, identifier:n; 132, string_content:graph | 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; 18, 30; 18, 31; 19, 32; 19, 33; 20, 34; 20, 35; 20, 36; 20, 37; 20, 38; 20, 39; 20, 40; 20, 41; 20, 42; 25, 43; 25, 44; 27, 45; 27, 46; 29, 47; 29, 48; 33, 49; 34, 50; 35, 51; 36, 52; 36, 53; 36, 54; 38, 55; 40, 56; 42, 57; 44, 58; 46, 59; 48, 60; 49, 61; 49, 62; 50, 63; 50, 64; 51, 65; 51, 66; 54, 67; 54, 68; 54, 69; 55, 70; 55, 71; 56, 72; 56, 73; 57, 74; 57, 75; 61, 76; 61, 77; 67, 78; 68, 79; 69, 80; 71, 81; 71, 82; 72, 83; 72, 84; 73, 85; 74, 86; 74, 87; 78, 88; 78, 89; 79, 90; 79, 91; 80, 92; 80, 93; 82, 94; 82, 95; 85, 96; 85, 97; 89, 98; 89, 99; 90, 100; 90, 101; 91, 102; 91, 103; 92, 104; 92, 105; 93, 106; 93, 107; 93, 108; 95, 109; 95, 110; 97, 111; 97, 112; 98, 113; 98, 114; 99, 115; 99, 116; 107, 117; 107, 118; 110, 119; 110, 120; 111, 121; 112, 122; 112, 123; 113, 124; 113, 125; 117, 126; 117, 127; 118, 128; 119, 129; 120, 130; 120, 131; 125, 132 | def __sort_adjacency_lists(dfs_data):
"""Sorts the adjacency list representation by the edge weights."""
new_adjacency_lists = {}
adjacency_lists = dfs_data['adj']
edge_weights = dfs_data['edge_weights']
edge_lookup = dfs_data['edge_lookup']
for node_id, adj_list in list(adjacency_lists.items()):
node_weight_lookup = {}
frond_lookup = {}
for node_b in adj_list:
edge_id = dfs_data['graph'].get_first_edge_id_by_node_ids(node_id, node_b)
node_weight_lookup[node_b] = edge_weights[edge_id]
frond_lookup[node_b] = 1 if edge_lookup[edge_id] == 'backedge' else 2
# Fronds should be before branches if the weights are equal
new_list = sorted(adj_list, key=lambda n: frond_lookup[n])
# Sort by weights
new_list.sort(key=lambda n: node_weight_lookup[n])
# Add the new sorted list to the new adjacency list lookup table
new_adjacency_lists[node_id] = new_list
return new_adjacency_lists |
0, module; 1, function_definition; 2, function_name:__edge_weight; 3, parameters; 4, block; 5, identifier:edge_id; 6, identifier:dfs_data; 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, expression_statement; 16, if_statement; 17, comment:"""Calculates the edge weight used to sort edges."""; 18, assignment; 19, assignment; 20, assignment; 21, assignment; 22, assignment; 23, assignment; 24, assignment; 25, assignment; 26, boolean_operator; 27, block; 28, elif_clause; 29, elif_clause; 30, else_clause; 31, identifier:graph; 32, subscript; 33, identifier:edge_lookup; 34, subscript; 35, identifier:edge; 36, call; 37, pattern_list; 38, subscript; 39, identifier:d_u; 40, call; 41, identifier:d_v; 42, call; 43, identifier:lp_1; 44, call; 45, identifier:d_lp_1; 46, call; 47, comparison_operator:edge_lookup[edge_id] == 'backedge'; 48, comparison_operator:d_v < d_u; 49, return_statement; 50, call; 51, block; 52, call; 53, block; 54, block; 55, identifier:dfs_data; 56, string; 57, identifier:dfs_data; 58, string; 59, attribute; 60, argument_list; 61, identifier:u; 62, identifier:v; 63, identifier:edge; 64, string; 65, identifier:D; 66, argument_list; 67, identifier:D; 68, argument_list; 69, identifier:L1; 70, argument_list; 71, identifier:D; 72, argument_list; 73, subscript; 74, string; 75, identifier:d_v; 76, identifier:d_u; 77, binary_operator:2*d_v; 78, identifier:is_type_I_branch; 79, argument_list; 80, return_statement; 81, identifier:is_type_II_branch; 82, argument_list; 83, return_statement; 84, return_statement; 85, string_content:graph; 86, string_content:edge_lookup; 87, identifier:graph; 88, identifier:get_edge; 89, identifier:edge_id; 90, string_content:vertices; 91, identifier:u; 92, identifier:dfs_data; 93, identifier:v; 94, identifier:dfs_data; 95, identifier:v; 96, identifier:dfs_data; 97, identifier:lp_1; 98, identifier:dfs_data; 99, identifier:edge_lookup; 100, identifier:edge_id; 101, string_content:backedge; 102, integer:2; 103, identifier:d_v; 104, identifier:u; 105, identifier:v; 106, identifier:dfs_data; 107, binary_operator:2*d_lp_1; 108, identifier:u; 109, identifier:v; 110, identifier:dfs_data; 111, binary_operator:2*d_lp_1 + 1; 112, binary_operator:2*graph.num_nodes() + 1; 113, integer:2; 114, identifier:d_lp_1; 115, binary_operator:2*d_lp_1; 116, integer:1; 117, binary_operator:2*graph.num_nodes(); 118, integer:1; 119, integer:2; 120, identifier:d_lp_1; 121, integer:2; 122, call; 123, attribute; 124, argument_list; 125, identifier:graph; 126, identifier:num_nodes | 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; 7, 17; 8, 18; 9, 19; 10, 20; 11, 21; 12, 22; 13, 23; 14, 24; 15, 25; 16, 26; 16, 27; 16, 28; 16, 29; 16, 30; 18, 31; 18, 32; 19, 33; 19, 34; 20, 35; 20, 36; 21, 37; 21, 38; 22, 39; 22, 40; 23, 41; 23, 42; 24, 43; 24, 44; 25, 45; 25, 46; 26, 47; 26, 48; 27, 49; 28, 50; 28, 51; 29, 52; 29, 53; 30, 54; 32, 55; 32, 56; 34, 57; 34, 58; 36, 59; 36, 60; 37, 61; 37, 62; 38, 63; 38, 64; 40, 65; 40, 66; 42, 67; 42, 68; 44, 69; 44, 70; 46, 71; 46, 72; 47, 73; 47, 74; 48, 75; 48, 76; 49, 77; 50, 78; 50, 79; 51, 80; 52, 81; 52, 82; 53, 83; 54, 84; 56, 85; 58, 86; 59, 87; 59, 88; 60, 89; 64, 90; 66, 91; 66, 92; 68, 93; 68, 94; 70, 95; 70, 96; 72, 97; 72, 98; 73, 99; 73, 100; 74, 101; 77, 102; 77, 103; 79, 104; 79, 105; 79, 106; 80, 107; 82, 108; 82, 109; 82, 110; 83, 111; 84, 112; 107, 113; 107, 114; 111, 115; 111, 116; 112, 117; 112, 118; 115, 119; 115, 120; 117, 121; 117, 122; 122, 123; 122, 124; 123, 125; 123, 126 | def __edge_weight(edge_id, dfs_data):
"""Calculates the edge weight used to sort edges."""
graph = dfs_data['graph']
edge_lookup = dfs_data['edge_lookup']
edge = graph.get_edge(edge_id)
u, v = edge['vertices']
d_u = D(u, dfs_data)
d_v = D(v, dfs_data)
lp_1 = L1(v, dfs_data)
d_lp_1 = D(lp_1, dfs_data)
if edge_lookup[edge_id] == 'backedge' and d_v < d_u:
return 2*d_v
elif is_type_I_branch(u, v, dfs_data):
return 2*d_lp_1
elif is_type_II_branch(u, v, dfs_data):
return 2*d_lp_1 + 1
else:
return 2*graph.num_nodes() + 1 |
0, module; 1, function_definition; 2, function_name:classify_segmented_recording; 3, parameters; 4, block; 5, identifier:recording; 6, default_parameter; 7, expression_statement; 8, global_statement; 9, if_statement; 10, return_statement; 11, identifier:result_format; 12, None; 13, comment:"""Use this function if you are sure you have a single symbol.
Parameters
----------
recording : string
The recording in JSON format
Returns
-------
list of dictionaries
Each dictionary contains the keys 'symbol' and 'probability'. The list
is sorted descending by probability.
"""; 14, identifier:single_symbol_classifier; 15, comparison_operator:single_symbol_classifier is None; 16, block; 17, call; 18, identifier:single_symbol_classifier; 19, None; 20, expression_statement; 21, attribute; 22, argument_list; 23, assignment; 24, identifier:single_symbol_classifier; 25, identifier:predict; 26, identifier:recording; 27, identifier:result_format; 28, identifier:single_symbol_classifier; 29, call; 30, identifier:SingleClassificer; 31, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 6, 12; 7, 13; 8, 14; 9, 15; 9, 16; 10, 17; 15, 18; 15, 19; 16, 20; 17, 21; 17, 22; 20, 23; 21, 24; 21, 25; 22, 26; 22, 27; 23, 28; 23, 29; 29, 30; 29, 31 | def classify_segmented_recording(recording, result_format=None):
"""Use this function if you are sure you have a single symbol.
Parameters
----------
recording : string
The recording in JSON format
Returns
-------
list of dictionaries
Each dictionary contains the keys 'symbol' and 'probability'. The list
is sorted descending by probability.
"""
global single_symbol_classifier
if single_symbol_classifier is None:
single_symbol_classifier = SingleClassificer()
return single_symbol_classifier.predict(recording, result_format) |
0, module; 1, function_definition; 2, function_name:sort_by_formula_id; 3, parameters; 4, block; 5, identifier:raw_datasets; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""
Sort a list of formulas by `id`, where `id` represents the accepted
formula id.
Parameters
----------
raw_datasets : list of dictionaries
A list of raw datasets.
Examples
--------
The parameter `raw_datasets` has to be of the format
>>> rd = [{'is_in_testset': 0,
... 'formula_id': 31,
... 'handwriting': HandwrittenData(raw_data_id=2953),
... 'formula_in_latex': 'A',
... 'id': 2953},
... {'is_in_testset': 0,
... 'formula_id': 31,
... 'handwriting': HandwrittenData(raw_data_id=4037),
... 'formula_in_latex': 'A',
... 'id': 4037},
... {'is_in_testset': 0,
... 'formula_id': 31,
... 'handwriting': HandwrittenData(raw_data_id=4056),
... 'formula_in_latex': 'A',
... 'id': 4056}]
>>> sort_by_formula_id(rd)
"""; 11, assignment; 12, identifier:el; 13, identifier:raw_datasets; 14, block; 15, identifier:by_formula_id; 16, identifier:by_formula_id; 17, call; 18, expression_statement; 19, identifier:defaultdict; 20, argument_list; 21, call; 22, identifier:list; 23, attribute; 24, argument_list; 25, subscript; 26, identifier:append; 27, subscript; 28, identifier:by_formula_id; 29, attribute; 30, identifier:el; 31, string; 32, subscript; 33, identifier:formula_id; 34, string_content:handwriting; 35, identifier:el; 36, string; 37, string_content:handwriting | 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; 17, 19; 17, 20; 18, 21; 20, 22; 21, 23; 21, 24; 23, 25; 23, 26; 24, 27; 25, 28; 25, 29; 27, 30; 27, 31; 29, 32; 29, 33; 31, 34; 32, 35; 32, 36; 36, 37 | def sort_by_formula_id(raw_datasets):
"""
Sort a list of formulas by `id`, where `id` represents the accepted
formula id.
Parameters
----------
raw_datasets : list of dictionaries
A list of raw datasets.
Examples
--------
The parameter `raw_datasets` has to be of the format
>>> rd = [{'is_in_testset': 0,
... 'formula_id': 31,
... 'handwriting': HandwrittenData(raw_data_id=2953),
... 'formula_in_latex': 'A',
... 'id': 2953},
... {'is_in_testset': 0,
... 'formula_id': 31,
... 'handwriting': HandwrittenData(raw_data_id=4037),
... 'formula_in_latex': 'A',
... 'id': 4037},
... {'is_in_testset': 0,
... 'formula_id': 31,
... 'handwriting': HandwrittenData(raw_data_id=4056),
... 'formula_in_latex': 'A',
... 'id': 4056}]
>>> sort_by_formula_id(rd)
"""
by_formula_id = defaultdict(list)
for el in raw_datasets:
by_formula_id[el['handwriting'].formula_id].append(el['handwriting'])
return by_formula_id |
0, module; 1, function_definition; 2, function_name:get_sorted_pointlist; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, expression_statement; 10, return_statement; 11, comment:"""
Make sure that the points and strokes are in order.
Returns
-------
list
A list of all strokes in the recording. Each stroke is represented
as a list of dicts {'time': 123, 'x': 45, 'y': 67}
"""; 12, assignment; 13, identifier:i; 14, call; 15, block; 16, assignment; 17, identifier:pointlist; 18, identifier:pointlist; 19, call; 20, identifier:range; 21, argument_list; 22, expression_statement; 23, identifier:pointlist; 24, call; 25, attribute; 26, argument_list; 27, call; 28, assignment; 29, identifier:sorted; 30, argument_list; 31, identifier:self; 32, identifier:get_pointlist; 33, identifier:len; 34, argument_list; 35, subscript; 36, call; 37, identifier:pointlist; 38, keyword_argument; 39, identifier:pointlist; 40, identifier:pointlist; 41, identifier:i; 42, identifier:sorted; 43, argument_list; 44, identifier:key; 45, lambda; 46, subscript; 47, keyword_argument; 48, lambda_parameters; 49, subscript; 50, identifier:pointlist; 51, identifier:i; 52, identifier:key; 53, lambda; 54, identifier:stroke; 55, subscript; 56, string; 57, lambda_parameters; 58, subscript; 59, identifier:stroke; 60, integer:0; 61, string_content:time; 62, identifier:p; 63, identifier:p; 64, string; 65, string_content:time | 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; 8, 14; 8, 15; 9, 16; 10, 17; 12, 18; 12, 19; 14, 20; 14, 21; 15, 22; 16, 23; 16, 24; 19, 25; 19, 26; 21, 27; 22, 28; 24, 29; 24, 30; 25, 31; 25, 32; 27, 33; 27, 34; 28, 35; 28, 36; 30, 37; 30, 38; 34, 39; 35, 40; 35, 41; 36, 42; 36, 43; 38, 44; 38, 45; 43, 46; 43, 47; 45, 48; 45, 49; 46, 50; 46, 51; 47, 52; 47, 53; 48, 54; 49, 55; 49, 56; 53, 57; 53, 58; 55, 59; 55, 60; 56, 61; 57, 62; 58, 63; 58, 64; 64, 65 | def get_sorted_pointlist(self):
"""
Make sure that the points and strokes are in order.
Returns
-------
list
A list of all strokes in the recording. Each stroke is represented
as a list of dicts {'time': 123, 'x': 45, 'y': 67}
"""
pointlist = self.get_pointlist()
for i in range(len(pointlist)):
pointlist[i] = sorted(pointlist[i], key=lambda p: p['time'])
pointlist = sorted(pointlist, key=lambda stroke: stroke[0]['time'])
return pointlist |
0, module; 1, function_definition; 2, function_name:get_name; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, if_statement; 10, return_statement; 11, identifier:use_alias; 12, True; 13, comment:"""
Gets the name to reference the sorted field
:return: the name to reference the sorted field
:rtype: str
"""; 14, attribute; 15, block; 16, else_clause; 17, identifier:use_alias; 18, block; 19, call; 20, identifier:self; 21, identifier:desc; 22, expression_statement; 23, block; 24, return_statement; 25, attribute; 26, argument_list; 27, assignment; 28, expression_statement; 29, call; 30, string; 31, identifier:format; 32, call; 33, identifier:direction; 34, identifier:direction; 35, string; 36, assignment; 37, attribute; 38, argument_list; 39, string_content:{0} {1}; 40, attribute; 41, argument_list; 42, string_content:DESC; 43, identifier:direction; 44, string; 45, string; 46, identifier:format; 47, call; 48, identifier:direction; 49, attribute; 50, identifier:get_select_sql; 51, string_content:ASC; 52, string_content:{0} {1}; 53, attribute; 54, argument_list; 55, identifier:self; 56, identifier:field; 57, attribute; 58, identifier:get_identifier; 59, identifier:self; 60, identifier:field | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 6, 12; 7, 13; 8, 14; 8, 15; 8, 16; 9, 17; 9, 18; 10, 19; 14, 20; 14, 21; 15, 22; 16, 23; 18, 24; 19, 25; 19, 26; 22, 27; 23, 28; 24, 29; 25, 30; 25, 31; 26, 32; 26, 33; 27, 34; 27, 35; 28, 36; 29, 37; 29, 38; 30, 39; 32, 40; 32, 41; 35, 42; 36, 43; 36, 44; 37, 45; 37, 46; 38, 47; 38, 48; 40, 49; 40, 50; 44, 51; 45, 52; 47, 53; 47, 54; 49, 55; 49, 56; 53, 57; 53, 58; 57, 59; 57, 60 | def get_name(self, use_alias=True):
"""
Gets the name to reference the sorted field
:return: the name to reference the sorted field
:rtype: str
"""
if self.desc:
direction = 'DESC'
else:
direction = 'ASC'
if use_alias:
return '{0} {1}'.format(self.field.get_identifier(), direction)
return '{0} {1}'.format(self.field.get_select_sql(), direction) |
0, module; 1, function_definition; 2, function_name:order_by; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, identifier:field; 13, None; 14, identifier:table; 15, None; 16, identifier:desc; 17, False; 18, comment:"""
Adds an order by clause to the query by adding a ``Sorter`` instance to the query's
sorters list
:type field: str or dict or :class:`Field <querybuilder.fields.Field>`
:param field: This can be a string of a field name, a dict of {'alias': field}, or
a ``Field`` instance
:type table: str or dict or :class:`Table <querybuilder.table.Table>`
:param table: Optional. This can be a string of a table name, a dict of {'alias': table}, or
a ``Table`` instance. A table only needs to be supplied in more complex queries where
the field name is ambiguous.
:type desc: bool
:param desc: Set to True to sort by this field in DESC order or False to sort by this field
in ASC order. Defaults to False.
:rtype: :class:`Query <querybuilder.query.Query>`
:return: self
"""; 19, call; 20, identifier:self; 21, attribute; 22, argument_list; 23, attribute; 24, identifier:append; 25, call; 26, identifier:self; 27, identifier:sorters; 28, identifier:Sorter; 29, argument_list; 30, keyword_argument; 31, keyword_argument; 32, keyword_argument; 33, identifier:field; 34, identifier:field; 35, identifier:table; 36, identifier:table; 37, identifier:desc; 38, identifier:desc | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 7, 15; 8, 16; 8, 17; 9, 18; 10, 19; 11, 20; 19, 21; 19, 22; 21, 23; 21, 24; 22, 25; 23, 26; 23, 27; 25, 28; 25, 29; 29, 30; 29, 31; 29, 32; 30, 33; 30, 34; 31, 35; 31, 36; 32, 37; 32, 38 | def order_by(self, field=None, table=None, desc=False):
"""
Adds an order by clause to the query by adding a ``Sorter`` instance to the query's
sorters list
:type field: str or dict or :class:`Field <querybuilder.fields.Field>`
:param field: This can be a string of a field name, a dict of {'alias': field}, or
a ``Field`` instance
:type table: str or dict or :class:`Table <querybuilder.table.Table>`
:param table: Optional. This can be a string of a table name, a dict of {'alias': table}, or
a ``Table`` instance. A table only needs to be supplied in more complex queries where
the field name is ambiguous.
:type desc: bool
:param desc: Set to True to sort by this field in DESC order or False to sort by this field
in ASC order. Defaults to False.
:rtype: :class:`Query <querybuilder.query.Query>`
:return: self
"""
self.sorters.append(Sorter(
field=field,
table=table,
desc=desc
))
return self |
0, module; 1, function_definition; 2, function_name:sort_by_tag; 3, parameters; 4, block; 5, identifier:self; 6, identifier:tag; 7, expression_statement; 8, return_statement; 9, comment:"""Sorts the `AmpalContainer` by a tag on the component objects.
Parameters
----------
tag : str
Key of tag used for sorting.
"""; 10, call; 11, identifier:AmpalContainer; 12, argument_list; 13, call; 14, identifier:sorted; 15, argument_list; 16, identifier:self; 17, keyword_argument; 18, identifier:key; 19, lambda; 20, lambda_parameters; 21, subscript; 22, identifier:x; 23, attribute; 24, identifier:tag; 25, identifier:x; 26, identifier:tags | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 7, 9; 8, 10; 10, 11; 10, 12; 12, 13; 13, 14; 13, 15; 15, 16; 15, 17; 17, 18; 17, 19; 19, 20; 19, 21; 20, 22; 21, 23; 21, 24; 23, 25; 23, 26 | def sort_by_tag(self, tag):
"""Sorts the `AmpalContainer` by a tag on the component objects.
Parameters
----------
tag : str
Key of tag used for sorting.
"""
return AmpalContainer(sorted(self, key=lambda x: x.tags[tag])) |
0, module; 1, function_definition; 2, function_name:fit_heptad_register; 3, parameters; 4, block; 5, identifier:crangles; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, comment:# This is dirty, too long but trimmed with zip; 13, expression_statement; 14, for_statement; 15, return_statement; 16, comment:"""Attempts to fit a heptad repeat to a set of Crick angles.
Parameters
----------
crangles: [float]
A list of average Crick angles for the coiled coil.
Returns
-------
fit_data: [(float, float, float)]
Sorted list of fits for each heptad position.
"""; 17, assignment; 18, assignment; 19, assignment; 20, assignment; 21, assignment; 22, assignment; 23, identifier:i; 24, call; 25, block; 26, call; 27, identifier:crangles; 28, list_comprehension; 29, identifier:hept_p; 30, list_comprehension; 31, identifier:ideal_crangs; 32, list; 33, identifier:full_hept; 34, binary_operator:len(crangles) // 7; 35, identifier:ideal_crang_list; 36, binary_operator:ideal_crangs * (full_hept + 2); 37, identifier:fitting; 38, list; 39, identifier:range; 40, argument_list; 41, expression_statement; 42, expression_statement; 43, expression_statement; 44, identifier:sorted; 45, argument_list; 46, conditional_expression:x if x > 0 else 360 + x; 47, for_in_clause; 48, binary_operator:x * (360.0 / 7.0) + ((360.0 / 7.0) / 2.0); 49, for_in_clause; 50, subscript; 51, subscript; 52, subscript; 53, subscript; 54, subscript; 55, subscript; 56, subscript; 57, call; 58, integer:7; 59, identifier:ideal_crangs; 60, parenthesized_expression; 61, integer:7; 62, assignment; 63, assignment; 64, call; 65, identifier:fitting; 66, keyword_argument; 67, identifier:x; 68, comparison_operator:x > 0; 69, binary_operator:360 + x; 70, identifier:x; 71, identifier:crangles; 72, binary_operator:x * (360.0 / 7.0); 73, parenthesized_expression; 74, identifier:x; 75, call; 76, identifier:hept_p; 77, integer:0; 78, identifier:hept_p; 79, integer:2; 80, identifier:hept_p; 81, integer:4; 82, identifier:hept_p; 83, integer:6; 84, identifier:hept_p; 85, integer:1; 86, identifier:hept_p; 87, integer:3; 88, identifier:hept_p; 89, integer:5; 90, identifier:len; 91, argument_list; 92, binary_operator:full_hept + 2; 93, identifier:ang_pairs; 94, call; 95, identifier:ang_diffs; 96, list_comprehension; 97, attribute; 98, argument_list; 99, identifier:key; 100, lambda; 101, identifier:x; 102, integer:0; 103, integer:360; 104, identifier:x; 105, identifier:x; 106, parenthesized_expression; 107, binary_operator:(360.0 / 7.0) / 2.0; 108, identifier:range; 109, argument_list; 110, identifier:crangles; 111, identifier:full_hept; 112, integer:2; 113, identifier:zip; 114, argument_list; 115, call; 116, for_in_clause; 117, identifier:fitting; 118, identifier:append; 119, tuple; 120, lambda_parameters; 121, subscript; 122, binary_operator:360.0 / 7.0; 123, parenthesized_expression; 124, float:2.0; 125, integer:7; 126, identifier:crangles; 127, subscript; 128, identifier:abs; 129, argument_list; 130, pattern_list; 131, identifier:ang_pairs; 132, identifier:i; 133, call; 134, call; 135, identifier:x; 136, identifier:x; 137, integer:1; 138, float:360.0; 139, float:7.0; 140, binary_operator:360.0 / 7.0; 141, identifier:ideal_crang_list; 142, slice; 143, binary_operator:y - x; 144, identifier:x; 145, identifier:y; 146, attribute; 147, argument_list; 148, attribute; 149, argument_list; 150, float:360.0; 151, float:7.0; 152, identifier:i; 153, identifier:y; 154, identifier:x; 155, identifier:numpy; 156, identifier:mean; 157, identifier:ang_diffs; 158, identifier:numpy; 159, identifier:std; 160, identifier:ang_diffs | 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; 10, 20; 11, 21; 13, 22; 14, 23; 14, 24; 14, 25; 15, 26; 17, 27; 17, 28; 18, 29; 18, 30; 19, 31; 19, 32; 20, 33; 20, 34; 21, 35; 21, 36; 22, 37; 22, 38; 24, 39; 24, 40; 25, 41; 25, 42; 25, 43; 26, 44; 26, 45; 28, 46; 28, 47; 30, 48; 30, 49; 32, 50; 32, 51; 32, 52; 32, 53; 32, 54; 32, 55; 32, 56; 34, 57; 34, 58; 36, 59; 36, 60; 40, 61; 41, 62; 42, 63; 43, 64; 45, 65; 45, 66; 46, 67; 46, 68; 46, 69; 47, 70; 47, 71; 48, 72; 48, 73; 49, 74; 49, 75; 50, 76; 50, 77; 51, 78; 51, 79; 52, 80; 52, 81; 53, 82; 53, 83; 54, 84; 54, 85; 55, 86; 55, 87; 56, 88; 56, 89; 57, 90; 57, 91; 60, 92; 62, 93; 62, 94; 63, 95; 63, 96; 64, 97; 64, 98; 66, 99; 66, 100; 68, 101; 68, 102; 69, 103; 69, 104; 72, 105; 72, 106; 73, 107; 75, 108; 75, 109; 91, 110; 92, 111; 92, 112; 94, 113; 94, 114; 96, 115; 96, 116; 97, 117; 97, 118; 98, 119; 100, 120; 100, 121; 106, 122; 107, 123; 107, 124; 109, 125; 114, 126; 114, 127; 115, 128; 115, 129; 116, 130; 116, 131; 119, 132; 119, 133; 119, 134; 120, 135; 121, 136; 121, 137; 122, 138; 122, 139; 123, 140; 127, 141; 127, 142; 129, 143; 130, 144; 130, 145; 133, 146; 133, 147; 134, 148; 134, 149; 140, 150; 140, 151; 142, 152; 143, 153; 143, 154; 146, 155; 146, 156; 147, 157; 148, 158; 148, 159; 149, 160 | def fit_heptad_register(crangles):
"""Attempts to fit a heptad repeat to a set of Crick angles.
Parameters
----------
crangles: [float]
A list of average Crick angles for the coiled coil.
Returns
-------
fit_data: [(float, float, float)]
Sorted list of fits for each heptad position.
"""
crangles = [x if x > 0 else 360 + x for x in crangles]
hept_p = [x * (360.0 / 7.0) + ((360.0 / 7.0) / 2.0) for x in range(7)]
ideal_crangs = [
hept_p[0],
hept_p[2],
hept_p[4],
hept_p[6],
hept_p[1],
hept_p[3],
hept_p[5]
]
full_hept = len(crangles) // 7
ideal_crang_list = ideal_crangs * (full_hept + 2) # This is dirty, too long but trimmed with zip
fitting = []
for i in range(7):
ang_pairs = zip(crangles, ideal_crang_list[i:])
ang_diffs = [abs(y - x) for x, y in ang_pairs]
fitting.append((i, numpy.mean(ang_diffs), numpy.std(ang_diffs)))
return sorted(fitting, key=lambda x: x[1]) |
0, module; 1, function_definition; 2, function_name:simplify; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, comment:# TODO: Refactor DualBase.simplify into different "sub-evals".; 8, comment:# If self is already canonical do nothing.; 9, if_statement; 10, comment:# Otherwise bring arguments into canonical form.; 11, expression_statement; 12, comment:# Create new instance of own class with canonical args.; 13, comment:# TODO: Only create new class if some args changed.; 14, expression_statement; 15, comment:# Literalize before doing anything, this also applies De Morgan's Law; 16, expression_statement; 17, comment:# Associativity:; 18, comment:# (A & B) & C = A & (B & C) = A & B & C; 19, comment:# (A | B) | C = A | (B | C) = A | B | C; 20, expression_statement; 21, comment:# Annihilation: A & 0 = 0, A | 1 = 1; 22, if_statement; 23, comment:# Idempotence: A & A = A, A | A = A; 24, comment:# this boils down to removing duplicates; 25, expression_statement; 26, for_statement; 27, if_statement; 28, comment:# Identity: A & 1 = A, A | 0 = A; 29, if_statement; 30, comment:# Complementation: A & ~A = 0, A | ~A = 1; 31, for_statement; 32, comment:# Elimination: (A & B) | (A & ~B) = A, (A | B) & (A | ~B) = A; 33, expression_statement; 34, while_statement; 35, comment:# Absorption: A & (A | B) = A, A | (A & B) = A; 36, comment:# Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B; 37, expression_statement; 38, if_statement; 39, comment:# Commutativity: A & B = B & A, A | B = B | A; 40, expression_statement; 41, comment:# Create new (now canonical) expression.; 42, expression_statement; 43, expression_statement; 44, return_statement; 45, comment:"""
Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Identity
- Complementation
- Elimination
- Absorption
- Commutativity (output is always sorted)
Other boolean objects are also in their canonical form.
"""; 46, attribute; 47, block; 48, assignment; 49, assignment; 50, assignment; 51, assignment; 52, comparison_operator:self.annihilator in expr.args; 53, block; 54, assignment; 55, identifier:arg; 56, attribute; 57, block; 58, comparison_operator:len(args) == 1; 59, block; 60, comparison_operator:self.identity in args; 61, block; 62, identifier:arg; 63, identifier:args; 64, block; 65, assignment; 66, comparison_operator:i < len(args) - 1; 67, block; 68, assignment; 69, comparison_operator:len(args) == 1; 70, block; 71, call; 72, assignment; 73, assignment; 74, identifier:expr; 75, identifier:self; 76, identifier:iscanonical; 77, return_statement; 78, identifier:args; 79, list_comprehension; 80, identifier:expr; 81, call; 82, identifier:expr; 83, call; 84, identifier:expr; 85, call; 86, attribute; 87, attribute; 88, return_statement; 89, identifier:args; 90, list; 91, identifier:expr; 92, identifier:args; 93, if_statement; 94, call; 95, integer:1; 96, return_statement; 97, attribute; 98, identifier:args; 99, expression_statement; 100, if_statement; 101, if_statement; 102, identifier:i; 103, integer:0; 104, identifier:i; 105, binary_operator:len(args) - 1; 106, expression_statement; 107, expression_statement; 108, if_statement; 109, while_statement; 110, expression_statement; 111, identifier:args; 112, call; 113, call; 114, integer:1; 115, return_statement; 116, attribute; 117, argument_list; 118, identifier:expr; 119, call; 120, attribute; 121, True; 122, identifier:self; 123, call; 124, for_in_clause; 125, attribute; 126, argument_list; 127, attribute; 128, argument_list; 129, attribute; 130, argument_list; 131, identifier:self; 132, identifier:annihilator; 133, identifier:expr; 134, identifier:args; 135, attribute; 136, comparison_operator:arg not in args; 137, block; 138, identifier:len; 139, argument_list; 140, subscript; 141, identifier:self; 142, identifier:identity; 143, call; 144, comparison_operator:len(args) == 1; 145, block; 146, comparison_operator:self.NOT(arg) in args; 147, block; 148, call; 149, integer:1; 150, assignment; 151, assignment; 152, not_operator; 153, block; 154, comparison_operator:j < len(args); 155, block; 156, augmented_assignment; 157, attribute; 158, argument_list; 159, identifier:len; 160, argument_list; 161, subscript; 162, identifier:args; 163, identifier:sort; 164, attribute; 165, argument_list; 166, identifier:expr; 167, identifier:iscanonical; 168, attribute; 169, argument_list; 170, identifier:arg; 171, attribute; 172, identifier:self; 173, identifier:__class__; 174, list_splat; 175, identifier:expr; 176, identifier:literalize; 177, identifier:expr; 178, identifier:flatten; 179, identifier:self; 180, identifier:annihilator; 181, identifier:arg; 182, identifier:args; 183, expression_statement; 184, identifier:args; 185, identifier:args; 186, integer:0; 187, attribute; 188, argument_list; 189, call; 190, integer:1; 191, return_statement; 192, call; 193, identifier:args; 194, return_statement; 195, identifier:len; 196, argument_list; 197, identifier:j; 198, binary_operator:i + 1; 199, identifier:ai; 200, subscript; 201, call; 202, expression_statement; 203, continue_statement; 204, identifier:j; 205, call; 206, expression_statement; 207, if_statement; 208, comment:# Find terms where only one arg is different.; 209, expression_statement; 210, for_statement; 211, comment:# If the different arg is a negation simplify the expr.; 212, if_statement; 213, expression_statement; 214, identifier:i; 215, integer:1; 216, identifier:self; 217, identifier:absorb; 218, identifier:args; 219, identifier:args; 220, identifier:args; 221, integer:0; 222, identifier:self; 223, identifier:__class__; 224, list_splat; 225, identifier:arg; 226, identifier:simplify; 227, identifier:self; 228, identifier:args; 229, identifier:args; 230, call; 231, identifier:args; 232, identifier:remove; 233, attribute; 234, identifier:len; 235, argument_list; 236, subscript; 237, attribute; 238, argument_list; 239, attribute; 240, identifier:args; 241, identifier:i; 242, integer:1; 243, identifier:args; 244, identifier:i; 245, identifier:isinstance; 246, argument_list; 247, augmented_assignment; 248, identifier:len; 249, argument_list; 250, assignment; 251, boolean_operator; 252, block; 253, assignment; 254, identifier:arg; 255, attribute; 256, comment:# FIXME: what does this pass Do?; 257, block; 258, comparison_operator:negated is not None; 259, comment:# Cancel out one of the two terms.; 260, block; 261, augmented_assignment; 262, identifier:args; 263, attribute; 264, argument_list; 265, identifier:self; 266, identifier:identity; 267, identifier:args; 268, identifier:args; 269, integer:0; 270, identifier:self; 271, identifier:NOT; 272, identifier:arg; 273, identifier:self; 274, identifier:annihilator; 275, identifier:ai; 276, attribute; 277, identifier:i; 278, integer:1; 279, identifier:args; 280, identifier:aj; 281, subscript; 282, not_operator; 283, comparison_operator:len(ai.args) != len(aj.args); 284, expression_statement; 285, continue_statement; 286, identifier:negated; 287, None; 288, identifier:ai; 289, identifier:args; 290, if_statement; 291, identifier:negated; 292, None; 293, delete_statement; 294, expression_statement; 295, expression_statement; 296, if_statement; 297, if_statement; 298, identifier:j; 299, integer:1; 300, identifier:args; 301, identifier:append; 302, identifier:arg; 303, identifier:self; 304, identifier:dual; 305, identifier:args; 306, identifier:j; 307, call; 308, call; 309, call; 310, augmented_assignment; 311, comparison_operator:arg in aj.args; 312, block; 313, elif_clause; 314, else_clause; 315, subscript; 316, assignment; 317, call; 318, comparison_operator:len(aiargs) == 1; 319, block; 320, else_clause; 321, comparison_operator:len(args) == 1; 322, block; 323, else_clause; 324, identifier:isinstance; 325, argument_list; 326, identifier:len; 327, argument_list; 328, identifier:len; 329, argument_list; 330, identifier:j; 331, integer:1; 332, identifier:arg; 333, attribute; 334, pass_statement; 335, comparison_operator:self.NOT(arg).cancel() in aj.args; 336, block; 337, block; 338, identifier:args; 339, identifier:j; 340, identifier:aiargs; 341, call; 342, attribute; 343, argument_list; 344, call; 345, integer:1; 346, expression_statement; 347, block; 348, call; 349, integer:1; 350, return_statement; 351, comment:# Now the other simplifications have to be redone.; 352, block; 353, identifier:aj; 354, attribute; 355, attribute; 356, attribute; 357, identifier:aj; 358, identifier:args; 359, call; 360, attribute; 361, if_statement; 362, expression_statement; 363, break_statement; 364, identifier:list; 365, argument_list; 366, identifier:aiargs; 367, identifier:remove; 368, identifier:negated; 369, identifier:len; 370, argument_list; 371, assignment; 372, expression_statement; 373, identifier:len; 374, argument_list; 375, subscript; 376, return_statement; 377, identifier:self; 378, identifier:dual; 379, identifier:ai; 380, identifier:args; 381, identifier:aj; 382, identifier:args; 383, attribute; 384, argument_list; 385, identifier:aj; 386, identifier:args; 387, comparison_operator:negated is None; 388, block; 389, else_clause; 390, assignment; 391, attribute; 392, identifier:aiargs; 393, subscript; 394, subscript; 395, assignment; 396, identifier:args; 397, identifier:args; 398, integer:0; 399, call; 400, call; 401, identifier:cancel; 402, identifier:negated; 403, None; 404, expression_statement; 405, block; 406, identifier:negated; 407, None; 408, identifier:ai; 409, identifier:args; 410, identifier:args; 411, identifier:i; 412, identifier:aiargs; 413, integer:0; 414, subscript; 415, call; 416, attribute; 417, argument_list; 418, attribute; 419, argument_list; 420, assignment; 421, expression_statement; 422, break_statement; 423, identifier:args; 424, identifier:i; 425, attribute; 426, argument_list; 427, call; 428, identifier:simplify; 429, identifier:self; 430, identifier:NOT; 431, identifier:arg; 432, identifier:negated; 433, identifier:arg; 434, assignment; 435, identifier:self; 436, identifier:dual; 437, list_splat; 438, attribute; 439, argument_list; 440, identifier:negated; 441, None; 442, identifier:aiargs; 443, identifier:self; 444, identifier:__class__; 445, list_splat; 446, identifier:args | 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; 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; 4, 42; 4, 43; 4, 44; 6, 45; 9, 46; 9, 47; 11, 48; 14, 49; 16, 50; 20, 51; 22, 52; 22, 53; 25, 54; 26, 55; 26, 56; 26, 57; 27, 58; 27, 59; 29, 60; 29, 61; 31, 62; 31, 63; 31, 64; 33, 65; 34, 66; 34, 67; 37, 68; 38, 69; 38, 70; 40, 71; 42, 72; 43, 73; 44, 74; 46, 75; 46, 76; 47, 77; 48, 78; 48, 79; 49, 80; 49, 81; 50, 82; 50, 83; 51, 84; 51, 85; 52, 86; 52, 87; 53, 88; 54, 89; 54, 90; 56, 91; 56, 92; 57, 93; 58, 94; 58, 95; 59, 96; 60, 97; 60, 98; 61, 99; 61, 100; 64, 101; 65, 102; 65, 103; 66, 104; 66, 105; 67, 106; 67, 107; 67, 108; 67, 109; 67, 110; 68, 111; 68, 112; 69, 113; 69, 114; 70, 115; 71, 116; 71, 117; 72, 118; 72, 119; 73, 120; 73, 121; 77, 122; 79, 123; 79, 124; 81, 125; 81, 126; 83, 127; 83, 128; 85, 129; 85, 130; 86, 131; 86, 132; 87, 133; 87, 134; 88, 135; 93, 136; 93, 137; 94, 138; 94, 139; 96, 140; 97, 141; 97, 142; 99, 143; 100, 144; 100, 145; 101, 146; 101, 147; 105, 148; 105, 149; 106, 150; 107, 151; 108, 152; 108, 153; 109, 154; 109, 155; 110, 156; 112, 157; 112, 158; 113, 159; 113, 160; 115, 161; 116, 162; 116, 163; 119, 164; 119, 165; 120, 166; 120, 167; 123, 168; 123, 169; 124, 170; 124, 171; 125, 172; 125, 173; 126, 174; 127, 175; 127, 176; 129, 177; 129, 178; 135, 179; 135, 180; 136, 181; 136, 182; 137, 183; 139, 184; 140, 185; 140, 186; 143, 187; 143, 188; 144, 189; 144, 190; 145, 191; 146, 192; 146, 193; 147, 194; 148, 195; 148, 196; 150, 197; 150, 198; 151, 199; 151, 200; 152, 201; 153, 202; 153, 203; 154, 204; 154, 205; 155, 206; 155, 207; 155, 208; 155, 209; 155, 210; 155, 211; 155, 212; 155, 213; 156, 214; 156, 215; 157, 216; 157, 217; 158, 218; 160, 219; 161, 220; 161, 221; 164, 222; 164, 223; 165, 224; 168, 225; 168, 226; 171, 227; 171, 228; 174, 229; 183, 230; 187, 231; 187, 232; 188, 233; 189, 234; 189, 235; 191, 236; 192, 237; 192, 238; 194, 239; 196, 240; 198, 241; 198, 242; 200, 243; 200, 244; 201, 245; 201, 246; 202, 247; 205, 248; 205, 249; 206, 250; 207, 251; 207, 252; 209, 253; 210, 254; 210, 255; 210, 256; 210, 257; 212, 258; 212, 259; 212, 260; 213, 261; 224, 262; 230, 263; 230, 264; 233, 265; 233, 266; 235, 267; 236, 268; 236, 269; 237, 270; 237, 271; 238, 272; 239, 273; 239, 274; 246, 275; 246, 276; 247, 277; 247, 278; 249, 279; 250, 280; 250, 281; 251, 282; 251, 283; 252, 284; 252, 285; 253, 286; 253, 287; 255, 288; 255, 289; 257, 290; 258, 291; 258, 292; 260, 293; 260, 294; 260, 295; 260, 296; 260, 297; 261, 298; 261, 299; 263, 300; 263, 301; 264, 302; 276, 303; 276, 304; 281, 305; 281, 306; 282, 307; 283, 308; 283, 309; 284, 310; 290, 311; 290, 312; 290, 313; 290, 314; 293, 315; 294, 316; 295, 317; 296, 318; 296, 319; 296, 320; 297, 321; 297, 322; 297, 323; 307, 324; 307, 325; 308, 326; 308, 327; 309, 328; 309, 329; 310, 330; 310, 331; 311, 332; 311, 333; 312, 334; 313, 335; 313, 336; 314, 337; 315, 338; 315, 339; 316, 340; 316, 341; 317, 342; 317, 343; 318, 344; 318, 345; 319, 346; 320, 347; 321, 348; 321, 349; 322, 350; 323, 351; 323, 352; 325, 353; 325, 354; 327, 355; 329, 356; 333, 357; 333, 358; 335, 359; 335, 360; 336, 361; 337, 362; 337, 363; 341, 364; 341, 365; 342, 366; 342, 367; 343, 368; 344, 369; 344, 370; 346, 371; 347, 372; 348, 373; 348, 374; 350, 375; 352, 376; 354, 377; 354, 378; 355, 379; 355, 380; 356, 381; 356, 382; 359, 383; 359, 384; 360, 385; 360, 386; 361, 387; 361, 388; 361, 389; 362, 390; 365, 391; 370, 392; 371, 393; 371, 394; 372, 395; 374, 396; 375, 397; 375, 398; 376, 399; 383, 400; 383, 401; 387, 402; 387, 403; 388, 404; 389, 405; 390, 406; 390, 407; 391, 408; 391, 409; 393, 410; 393, 411; 394, 412; 394, 413; 395, 414; 395, 415; 399, 416; 399, 417; 400, 418; 400, 419; 404, 420; 405, 421; 405, 422; 414, 423; 414, 424; 415, 425; 415, 426; 416, 427; 416, 428; 418, 429; 418, 430; 419, 431; 420, 432; 420, 433; 421, 434; 425, 435; 425, 436; 426, 437; 427, 438; 427, 439; 434, 440; 434, 441; 437, 442; 438, 443; 438, 444; 439, 445; 445, 446 | def simplify(self):
"""
Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Identity
- Complementation
- Elimination
- Absorption
- Commutativity (output is always sorted)
Other boolean objects are also in their canonical form.
"""
# TODO: Refactor DualBase.simplify into different "sub-evals".
# If self is already canonical do nothing.
if self.iscanonical:
return self
# Otherwise bring arguments into canonical form.
args = [arg.simplify() for arg in self.args]
# Create new instance of own class with canonical args.
# TODO: Only create new class if some args changed.
expr = self.__class__(*args)
# Literalize before doing anything, this also applies De Morgan's Law
expr = expr.literalize()
# Associativity:
# (A & B) & C = A & (B & C) = A & B & C
# (A | B) | C = A | (B | C) = A | B | C
expr = expr.flatten()
# Annihilation: A & 0 = 0, A | 1 = 1
if self.annihilator in expr.args:
return self.annihilator
# Idempotence: A & A = A, A | A = A
# this boils down to removing duplicates
args = []
for arg in expr.args:
if arg not in args:
args.append(arg)
if len(args) == 1:
return args[0]
# Identity: A & 1 = A, A | 0 = A
if self.identity in args:
args.remove(self.identity)
if len(args) == 1:
return args[0]
# Complementation: A & ~A = 0, A | ~A = 1
for arg in args:
if self.NOT(arg) in args:
return self.annihilator
# Elimination: (A & B) | (A & ~B) = A, (A | B) & (A | ~B) = A
i = 0
while i < len(args) - 1:
j = i + 1
ai = args[i]
if not isinstance(ai, self.dual):
i += 1
continue
while j < len(args):
aj = args[j]
if not isinstance(aj, self.dual) or len(ai.args) != len(aj.args):
j += 1
continue
# Find terms where only one arg is different.
negated = None
for arg in ai.args:
# FIXME: what does this pass Do?
if arg in aj.args:
pass
elif self.NOT(arg).cancel() in aj.args:
if negated is None:
negated = arg
else:
negated = None
break
else:
negated = None
break
# If the different arg is a negation simplify the expr.
if negated is not None:
# Cancel out one of the two terms.
del args[j]
aiargs = list(ai.args)
aiargs.remove(negated)
if len(aiargs) == 1:
args[i] = aiargs[0]
else:
args[i] = self.dual(*aiargs)
if len(args) == 1:
return args[0]
else:
# Now the other simplifications have to be redone.
return self.__class__(*args).simplify()
j += 1
i += 1
# Absorption: A & (A | B) = A, A | (A & B) = A
# Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
args = self.absorb(args)
if len(args) == 1:
return args[0]
# Commutativity: A & B = B & A, A | B = B | A
args.sort()
# Create new (now canonical) expression.
expr = self.__class__(*args)
expr.iscanonical = True
return expr |
0, module; 1, function_definition; 2, function_name:_recordAndPrintHeadline; 3, parameters; 4, block; 5, identifier:self; 6, identifier:test; 7, identifier:error_class; 8, identifier:artifact; 9, expression_statement; 10, comment:# We duplicate the errorclass handling from super rather than calling; 11, comment:# it and monkeying around with showAll flags to keep it from printing; 12, comment:# anything.; 13, expression_statement; 14, for_statement; 15, if_statement; 16, expression_statement; 17, expression_statement; 18, return_statement; 19, comment:"""Record that an error-like thing occurred, and print a summary.
Store ``artifact`` with the record.
Return whether the test result is any sort of failure.
"""; 20, assignment; 21, pattern_list; 22, call; 23, block; 24, not_operator; 25, block; 26, assignment; 27, call; 28, identifier:is_any_failure; 29, identifier:is_error_class; 30, False; 31, identifier:cls; 32, tuple_pattern; 33, attribute; 34, argument_list; 35, if_statement; 36, identifier:is_error_class; 37, expression_statement; 38, expression_statement; 39, identifier:is_any_failure; 40, boolean_operator; 41, attribute; 42, argument_list; 43, identifier:storage; 44, identifier:label; 45, identifier:is_failure; 46, attribute; 47, identifier:items; 48, boolean_operator; 49, block; 50, call; 51, assignment; 52, not_operator; 53, identifier:is_failure; 54, identifier:self; 55, identifier:_printHeadline; 56, conditional_expression:label if is_error_class else 'ERROR'; 57, identifier:test; 58, keyword_argument; 59, identifier:self; 60, identifier:errorClasses; 61, call; 62, call; 63, if_statement; 64, expression_statement; 65, expression_statement; 66, attribute; 67, argument_list; 68, attribute; 69, False; 70, identifier:is_error_class; 71, identifier:label; 72, identifier:is_error_class; 73, string; 74, identifier:is_failure; 75, identifier:is_any_failure; 76, identifier:isclass; 77, argument_list; 78, identifier:issubclass; 79, argument_list; 80, identifier:is_failure; 81, block; 82, call; 83, assignment; 84, attribute; 85, identifier:append; 86, tuple; 87, identifier:test; 88, identifier:passed; 89, string_content:ERROR; 90, identifier:error_class; 91, identifier:error_class; 92, identifier:cls; 93, expression_statement; 94, attribute; 95, argument_list; 96, identifier:is_error_class; 97, True; 98, identifier:self; 99, identifier:errors; 100, identifier:test; 101, identifier:artifact; 102, assignment; 103, identifier:storage; 104, identifier:append; 105, tuple; 106, attribute; 107, False; 108, identifier:test; 109, identifier:artifact; 110, identifier:test; 111, identifier:passed | 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; 13, 20; 14, 21; 14, 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; 24, 36; 25, 37; 25, 38; 26, 39; 26, 40; 27, 41; 27, 42; 32, 43; 32, 44; 32, 45; 33, 46; 33, 47; 35, 48; 35, 49; 37, 50; 38, 51; 40, 52; 40, 53; 41, 54; 41, 55; 42, 56; 42, 57; 42, 58; 46, 59; 46, 60; 48, 61; 48, 62; 49, 63; 49, 64; 49, 65; 50, 66; 50, 67; 51, 68; 51, 69; 52, 70; 56, 71; 56, 72; 56, 73; 58, 74; 58, 75; 61, 76; 61, 77; 62, 78; 62, 79; 63, 80; 63, 81; 64, 82; 65, 83; 66, 84; 66, 85; 67, 86; 68, 87; 68, 88; 73, 89; 77, 90; 79, 91; 79, 92; 81, 93; 82, 94; 82, 95; 83, 96; 83, 97; 84, 98; 84, 99; 86, 100; 86, 101; 93, 102; 94, 103; 94, 104; 95, 105; 102, 106; 102, 107; 105, 108; 105, 109; 106, 110; 106, 111 | def _recordAndPrintHeadline(self, test, error_class, artifact):
"""Record that an error-like thing occurred, and print a summary.
Store ``artifact`` with the record.
Return whether the test result is any sort of failure.
"""
# We duplicate the errorclass handling from super rather than calling
# it and monkeying around with showAll flags to keep it from printing
# anything.
is_error_class = False
for cls, (storage, label, is_failure) in self.errorClasses.items():
if isclass(error_class) and issubclass(error_class, cls):
if is_failure:
test.passed = False
storage.append((test, artifact))
is_error_class = True
if not is_error_class:
self.errors.append((test, artifact))
test.passed = False
is_any_failure = not is_error_class or is_failure
self._printHeadline(label if is_error_class else 'ERROR',
test,
is_failure=is_any_failure)
return is_any_failure |
0, module; 1, function_definition; 2, function_name:_decode_filename_to_unicode; 3, parameters; 4, block; 5, identifier:f; 6, expression_statement; 7, expression_statement; 8, if_statement; 9, try_statement; 10, string; 11, call; 12, call; 13, block; 14, block; 15, except_clause; 16, string_content:Get bytestring filename and return unicode.
First, try to decode from default file system encoding
If that fails, use ``chardet`` module to guess encoding.
As a last resort, try to decode as utf-8.
If the argument already is unicode, return as is; 17, attribute; 18, argument_list; 19, identifier:isinstance; 20, argument_list; 21, return_statement; 22, return_statement; 23, identifier:UnicodeDecodeError; 24, block; 25, identifier:log; 26, identifier:debug; 27, string; 28, call; 29, identifier:f; 30, identifier:unicode; 31, identifier:f; 32, call; 33, expression_statement; 34, expression_statement; 35, if_statement; 36, expression_statement; 37, expression_statement; 38, try_statement; 39, expression_statement; 40, try_statement; 41, string_content:_decode_filename_to_unicode(%s); 42, identifier:repr; 43, argument_list; 44, attribute; 45, argument_list; 46, assignment; 47, call; 48, comparison_operator:charguess['encoding'] is not None; 49, block; 50, call; 51, call; 52, block; 53, except_clause; 54, call; 55, block; 56, except_clause; 57, identifier:f; 58, identifier:f; 59, identifier:decode; 60, call; 61, identifier:charguess; 62, call; 63, attribute; 64, argument_list; 65, subscript; 66, None; 67, try_statement; 68, attribute; 69, argument_list; 70, attribute; 71, argument_list; 72, return_statement; 73, identifier:UnicodeDecodeError; 74, block; 75, attribute; 76, argument_list; 77, return_statement; 78, identifier:UnicodeDecodeError; 79, block; 80, attribute; 81, argument_list; 82, attribute; 83, argument_list; 84, identifier:log; 85, identifier:debug; 86, string:"chardet filename: %r -> %r"; 87, identifier:f; 88, identifier:charguess; 89, identifier:charguess; 90, string; 91, block; 92, except_clause; 93, identifier:log; 94, identifier:warning; 95, string; 96, identifier:f; 97, identifier:charguess; 98, identifier:log; 99, identifier:debug; 100, string; 101, identifier:f; 102, call; 103, pass_statement; 104, identifier:log; 105, identifier:debug; 106, string; 107, identifier:f; 108, call; 109, expression_statement; 110, return_statement; 111, identifier:sys; 112, identifier:getfilesystemencoding; 113, identifier:chardet; 114, identifier:detect; 115, identifier:f; 116, string_content:encoding; 117, return_statement; 118, identifier:UnicodeDecodeError; 119, block; 120, string_content:Cannot understand decoding of this filename: %r (guessed %r, but was wrong); 121, string_content:Trying utf-8 to decode %r; 122, attribute; 123, argument_list; 124, string_content:Trying latin1 to decode %r; 125, attribute; 126, argument_list; 127, call; 128, call; 129, call; 130, pass_statement; 131, identifier:f; 132, identifier:decode; 133, string; 134, identifier:f; 135, identifier:decode; 136, string; 137, attribute; 138, argument_list; 139, attribute; 140, argument_list; 141, attribute; 142, argument_list; 143, string_content:utf-8; 144, string_content:latin1; 145, identifier:log; 146, identifier:warning; 147, string; 148, identifier:f; 149, identifier:f; 150, identifier:decode; 151, string; 152, keyword_argument; 153, identifier:f; 154, identifier:decode; 155, subscript; 156, string_content:Exhausted all options. Decoding %r to safe ascii; 157, string_content:ascii; 158, identifier:errors; 159, string; 160, identifier:charguess; 161, string; 162, string_content:ignore; 163, string_content:encoding | 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; 9, 15; 10, 16; 11, 17; 11, 18; 12, 19; 12, 20; 13, 21; 14, 22; 15, 23; 15, 24; 17, 25; 17, 26; 18, 27; 18, 28; 20, 29; 20, 30; 21, 31; 22, 32; 24, 33; 24, 34; 24, 35; 24, 36; 24, 37; 24, 38; 24, 39; 24, 40; 27, 41; 28, 42; 28, 43; 32, 44; 32, 45; 33, 46; 34, 47; 35, 48; 35, 49; 36, 50; 37, 51; 38, 52; 38, 53; 39, 54; 40, 55; 40, 56; 43, 57; 44, 58; 44, 59; 45, 60; 46, 61; 46, 62; 47, 63; 47, 64; 48, 65; 48, 66; 49, 67; 50, 68; 50, 69; 51, 70; 51, 71; 52, 72; 53, 73; 53, 74; 54, 75; 54, 76; 55, 77; 56, 78; 56, 79; 60, 80; 60, 81; 62, 82; 62, 83; 63, 84; 63, 85; 64, 86; 64, 87; 64, 88; 65, 89; 65, 90; 67, 91; 67, 92; 68, 93; 68, 94; 69, 95; 69, 96; 69, 97; 70, 98; 70, 99; 71, 100; 71, 101; 72, 102; 74, 103; 75, 104; 75, 105; 76, 106; 76, 107; 77, 108; 79, 109; 79, 110; 80, 111; 80, 112; 82, 113; 82, 114; 83, 115; 90, 116; 91, 117; 92, 118; 92, 119; 95, 120; 100, 121; 102, 122; 102, 123; 106, 124; 108, 125; 108, 126; 109, 127; 110, 128; 117, 129; 119, 130; 122, 131; 122, 132; 123, 133; 125, 134; 125, 135; 126, 136; 127, 137; 127, 138; 128, 139; 128, 140; 129, 141; 129, 142; 133, 143; 136, 144; 137, 145; 137, 146; 138, 147; 138, 148; 139, 149; 139, 150; 140, 151; 140, 152; 141, 153; 141, 154; 142, 155; 147, 156; 151, 157; 152, 158; 152, 159; 155, 160; 155, 161; 159, 162; 161, 163 | def _decode_filename_to_unicode(f):
'''Get bytestring filename and return unicode.
First, try to decode from default file system encoding
If that fails, use ``chardet`` module to guess encoding.
As a last resort, try to decode as utf-8.
If the argument already is unicode, return as is'''
log.debug('_decode_filename_to_unicode(%s)', repr(f))
if isinstance(f, unicode):
return f
try:
return f.decode(sys.getfilesystemencoding())
except UnicodeDecodeError:
charguess = chardet.detect(f)
log.debug("chardet filename: %r -> %r", f, charguess)
if charguess['encoding'] is not None:
try:
return f.decode(charguess['encoding'])
except UnicodeDecodeError:
pass
log.warning('Cannot understand decoding of this filename: %r (guessed %r, but was wrong)',
f, charguess)
log.debug('Trying utf-8 to decode %r', f)
try:
return f.decode('utf-8')
except UnicodeDecodeError:
pass
log.debug('Trying latin1 to decode %r', f)
try:
return f.decode('latin1')
except UnicodeDecodeError:
log.warning('Exhausted all options. Decoding %r to safe ascii', f)
return f.decode('ascii', errors='ignore') |
0, module; 1, function_definition; 2, function_name:sortBy; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, identifier:val; 10, None; 11, comment:""" Sort the object's values by a criterion produced by an iterator.
"""; 12, comparison_operator:val is not None; 13, block; 14, else_clause; 15, identifier:val; 16, None; 17, if_statement; 18, block; 19, call; 20, block; 21, else_clause; 22, return_statement; 23, attribute; 24, argument_list; 25, return_statement; 26, block; 27, call; 28, call; 29, identifier:isString; 30, call; 31, return_statement; 32, attribute; 33, argument_list; 34, identifier:_; 35, argument_list; 36, attribute; 37, argument_list; 38, call; 39, identifier:self; 40, identifier:_wrap; 41, call; 42, identifier:val; 43, identifier:self; 44, identifier:_wrap; 45, call; 46, attribute; 47, argument_list; 48, identifier:sorted; 49, argument_list; 50, identifier:sorted; 51, argument_list; 52, identifier:self; 53, identifier:_wrap; 54, call; 55, attribute; 56, attribute; 57, keyword_argument; 58, identifier:sorted; 59, argument_list; 60, identifier:self; 61, identifier:obj; 62, identifier:self; 63, identifier:obj; 64, identifier:key; 65, lambda; 66, attribute; 67, keyword_argument; 68, lambda_parameters; 69, call; 70, identifier:self; 71, identifier:obj; 72, identifier:key; 73, identifier:val; 74, identifier:x; 75, list_splat_pattern; 76, attribute; 77, argument_list; 78, identifier:args; 79, identifier:x; 80, identifier:get; 81, identifier:val | 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; 12, 15; 12, 16; 13, 17; 14, 18; 17, 19; 17, 20; 17, 21; 18, 22; 19, 23; 19, 24; 20, 25; 21, 26; 22, 27; 23, 28; 23, 29; 25, 30; 26, 31; 27, 32; 27, 33; 28, 34; 28, 35; 30, 36; 30, 37; 31, 38; 32, 39; 32, 40; 33, 41; 35, 42; 36, 43; 36, 44; 37, 45; 38, 46; 38, 47; 41, 48; 41, 49; 45, 50; 45, 51; 46, 52; 46, 53; 47, 54; 49, 55; 51, 56; 51, 57; 54, 58; 54, 59; 55, 60; 55, 61; 56, 62; 56, 63; 57, 64; 57, 65; 59, 66; 59, 67; 65, 68; 65, 69; 66, 70; 66, 71; 67, 72; 67, 73; 68, 74; 68, 75; 69, 76; 69, 77; 75, 78; 76, 79; 76, 80; 77, 81 | def sortBy(self, val=None):
""" Sort the object's values by a criterion produced by an iterator.
"""
if val is not None:
if _(val).isString():
return self._wrap(sorted(self.obj, key=lambda x,
*args: x.get(val)))
else:
return self._wrap(sorted(self.obj, key=val))
else:
return self._wrap(sorted(self.obj)) |
0, module; 1, function_definition; 2, function_name:sortedIndex; 3, parameters; 4, block; 5, identifier:self; 6, identifier:obj; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, while_statement; 14, return_statement; 15, identifier:iterator; 16, lambda; 17, comment:"""
Use a comparator function to figure out the smallest index at which
an object should be inserted so as to maintain order.
Uses binary search.
"""; 18, assignment; 19, assignment; 20, assignment; 21, assignment; 22, comparison_operator:low < high; 23, block; 24, call; 25, lambda_parameters; 26, identifier:x; 27, identifier:array; 28, attribute; 29, identifier:value; 30, call; 31, identifier:low; 32, integer:0; 33, identifier:high; 34, call; 35, identifier:low; 36, identifier:high; 37, expression_statement; 38, if_statement; 39, attribute; 40, argument_list; 41, identifier:x; 42, identifier:self; 43, identifier:obj; 44, identifier:iterator; 45, argument_list; 46, identifier:len; 47, argument_list; 48, assignment; 49, comparison_operator:iterator(array[mid]) < value; 50, block; 51, else_clause; 52, identifier:self; 53, identifier:_wrap; 54, identifier:low; 55, identifier:obj; 56, identifier:array; 57, identifier:mid; 58, binary_operator:(low + high) >> 1; 59, call; 60, identifier:value; 61, expression_statement; 62, block; 63, parenthesized_expression; 64, integer:1; 65, identifier:iterator; 66, argument_list; 67, assignment; 68, expression_statement; 69, binary_operator:low + high; 70, subscript; 71, identifier:low; 72, binary_operator:mid + 1; 73, assignment; 74, identifier:low; 75, identifier:high; 76, identifier:array; 77, identifier:mid; 78, identifier:mid; 79, integer:1; 80, identifier:high; 81, identifier:mid | 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; 7, 15; 7, 16; 8, 17; 9, 18; 10, 19; 11, 20; 12, 21; 13, 22; 13, 23; 14, 24; 16, 25; 16, 26; 18, 27; 18, 28; 19, 29; 19, 30; 20, 31; 20, 32; 21, 33; 21, 34; 22, 35; 22, 36; 23, 37; 23, 38; 24, 39; 24, 40; 25, 41; 28, 42; 28, 43; 30, 44; 30, 45; 34, 46; 34, 47; 37, 48; 38, 49; 38, 50; 38, 51; 39, 52; 39, 53; 40, 54; 45, 55; 47, 56; 48, 57; 48, 58; 49, 59; 49, 60; 50, 61; 51, 62; 58, 63; 58, 64; 59, 65; 59, 66; 61, 67; 62, 68; 63, 69; 66, 70; 67, 71; 67, 72; 68, 73; 69, 74; 69, 75; 70, 76; 70, 77; 72, 78; 72, 79; 73, 80; 73, 81 | def sortedIndex(self, obj, iterator=lambda x: x):
"""
Use a comparator function to figure out the smallest index at which
an object should be inserted so as to maintain order.
Uses binary search.
"""
array = self.obj
value = iterator(obj)
low = 0
high = len(array)
while low < high:
mid = (low + high) >> 1
if iterator(array[mid]) < value:
low = mid + 1
else:
high = mid
return self._wrap(low) |
0, module; 1, function_definition; 2, function_name:uniq; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, function_definition; 15, expression_statement; 16, return_statement; 17, identifier:isSorted; 18, False; 19, identifier:iterator; 20, None; 21, comment:"""
Produce a duplicate-free version of the array. If the array has already
been sorted, you have the option of using a faster algorithm.
Aliased as `unique`.
"""; 22, assignment; 23, assignment; 24, assignment; 25, assignment; 26, comparison_operator:iterator is not None; 27, block; 28, function_name:by; 29, parameters; 30, block; 31, assignment; 32, call; 33, identifier:ns; 34, call; 35, attribute; 36, list; 37, attribute; 38, attribute; 39, identifier:initial; 40, attribute; 41, identifier:iterator; 42, None; 43, expression_statement; 44, identifier:memo; 45, identifier:value; 46, identifier:index; 47, if_statement; 48, return_statement; 49, identifier:ret; 50, call; 51, attribute; 52, argument_list; 53, attribute; 54, argument_list; 55, identifier:ns; 56, identifier:results; 57, identifier:ns; 58, identifier:array; 59, identifier:self; 60, identifier:obj; 61, identifier:self; 62, identifier:obj; 63, assignment; 64, parenthesized_expression; 65, block; 66, identifier:memo; 67, attribute; 68, argument_list; 69, identifier:self; 70, identifier:_wrap; 71, identifier:ret; 72, identifier:self; 73, identifier:Namespace; 74, identifier:initial; 75, call; 76, conditional_expression:(_.last(memo) != value or
not len(memo)) if isSorted else not _.include(memo, value); 77, expression_statement; 78, expression_statement; 79, identifier:_; 80, identifier:reduce; 81, identifier:initial; 82, identifier:by; 83, attribute; 84, argument_list; 85, parenthesized_expression; 86, identifier:isSorted; 87, not_operator; 88, call; 89, call; 90, call; 91, identifier:map; 92, identifier:iterator; 93, boolean_operator; 94, call; 95, attribute; 96, argument_list; 97, attribute; 98, argument_list; 99, identifier:_; 100, argument_list; 101, comparison_operator:_.last(memo) != value; 102, not_operator; 103, attribute; 104, argument_list; 105, identifier:memo; 106, identifier:append; 107, identifier:value; 108, attribute; 109, identifier:append; 110, subscript; 111, attribute; 112, call; 113, identifier:value; 114, call; 115, identifier:_; 116, identifier:include; 117, identifier:memo; 118, identifier:value; 119, identifier:ns; 120, identifier:results; 121, attribute; 122, identifier:index; 123, identifier:ns; 124, identifier:array; 125, attribute; 126, argument_list; 127, identifier:len; 128, argument_list; 129, identifier:ns; 130, identifier:array; 131, identifier:_; 132, identifier:last; 133, identifier:memo; 134, identifier:memo | 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; 4, 16; 6, 17; 6, 18; 7, 19; 7, 20; 8, 21; 9, 22; 10, 23; 11, 24; 12, 25; 13, 26; 13, 27; 14, 28; 14, 29; 14, 30; 15, 31; 16, 32; 22, 33; 22, 34; 23, 35; 23, 36; 24, 37; 24, 38; 25, 39; 25, 40; 26, 41; 26, 42; 27, 43; 29, 44; 29, 45; 29, 46; 30, 47; 30, 48; 31, 49; 31, 50; 32, 51; 32, 52; 34, 53; 34, 54; 35, 55; 35, 56; 37, 57; 37, 58; 38, 59; 38, 60; 40, 61; 40, 62; 43, 63; 47, 64; 47, 65; 48, 66; 50, 67; 50, 68; 51, 69; 51, 70; 52, 71; 53, 72; 53, 73; 63, 74; 63, 75; 64, 76; 65, 77; 65, 78; 67, 79; 67, 80; 68, 81; 68, 82; 75, 83; 75, 84; 76, 85; 76, 86; 76, 87; 77, 88; 78, 89; 83, 90; 83, 91; 84, 92; 85, 93; 87, 94; 88, 95; 88, 96; 89, 97; 89, 98; 90, 99; 90, 100; 93, 101; 93, 102; 94, 103; 94, 104; 95, 105; 95, 106; 96, 107; 97, 108; 97, 109; 98, 110; 100, 111; 101, 112; 101, 113; 102, 114; 103, 115; 103, 116; 104, 117; 104, 118; 108, 119; 108, 120; 110, 121; 110, 122; 111, 123; 111, 124; 112, 125; 112, 126; 114, 127; 114, 128; 121, 129; 121, 130; 125, 131; 125, 132; 126, 133; 128, 134 | def uniq(self, isSorted=False, iterator=None):
"""
Produce a duplicate-free version of the array. If the array has already
been sorted, you have the option of using a faster algorithm.
Aliased as `unique`.
"""
ns = self.Namespace()
ns.results = []
ns.array = self.obj
initial = self.obj
if iterator is not None:
initial = _(ns.array).map(iterator)
def by(memo, value, index):
if ((_.last(memo) != value or
not len(memo)) if isSorted else not _.include(memo, value)):
memo.append(value)
ns.results.append(ns.array[index])
return memo
ret = _.reduce(initial, by)
return self._wrap(ret) |
0, module; 1, function_definition; 2, function_name:functions; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:""" Return a sorted list of the function names available on the object.
"""; 11, assignment; 12, pattern_list; 13, call; 14, block; 15, call; 16, identifier:names; 17, list; 18, identifier:i; 19, identifier:k; 20, identifier:enumerate; 21, argument_list; 22, if_statement; 23, attribute; 24, argument_list; 25, attribute; 26, call; 27, block; 28, identifier:self; 29, identifier:_wrap; 30, call; 31, identifier:self; 32, identifier:obj; 33, attribute; 34, argument_list; 35, expression_statement; 36, identifier:sorted; 37, argument_list; 38, call; 39, identifier:isCallable; 40, call; 41, identifier:names; 42, identifier:_; 43, argument_list; 44, attribute; 45, argument_list; 46, subscript; 47, identifier:names; 48, identifier:append; 49, identifier:k; 50, attribute; 51, identifier:k; 52, identifier:self; 53, identifier:obj | 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; 15, 23; 15, 24; 21, 25; 22, 26; 22, 27; 23, 28; 23, 29; 24, 30; 25, 31; 25, 32; 26, 33; 26, 34; 27, 35; 30, 36; 30, 37; 33, 38; 33, 39; 35, 40; 37, 41; 38, 42; 38, 43; 40, 44; 40, 45; 43, 46; 44, 47; 44, 48; 45, 49; 46, 50; 46, 51; 50, 52; 50, 53 | def functions(self):
""" Return a sorted list of the function names available on the object.
"""
names = []
for i, k in enumerate(self.obj):
if _(self.obj[k]).isCallable():
names.append(k)
return self._wrap(sorted(names)) |
0, module; 1, function_definition; 2, function_name:createMSBWTFromBam; 3, parameters; 4, block; 5, identifier:bamFNs; 6, identifier:outputDir; 7, identifier:numProcs; 8, identifier:areUniform; 9, identifier:logger; 10, expression_statement; 11, comment:#generate the files we will reference and clear out the in memory array before making the BWT; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, string; 21, call; 22, assignment; 23, assignment; 24, assignment; 25, assignment; 26, call; 27, call; 28, call; 29, string_content:This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer
@param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME
@param outputDir - the directory for all of the bwt related data
@param numProcs - the number of processes it's allowed to use
@areUniform - true if all the sequences passed into the function are of equal length; 30, attribute; 31, argument_list; 32, identifier:seqFN; 33, binary_operator:outputDir+'/seqs.npy'; 34, identifier:offsetFN; 35, binary_operator:outputDir+'/offsets.npy'; 36, identifier:abtFN; 37, binary_operator:outputDir+'/about.npy'; 38, identifier:bwtFN; 39, binary_operator:outputDir+'/msbwt.npy'; 40, attribute; 41, argument_list; 42, identifier:preprocessBams; 43, argument_list; 44, attribute; 45, argument_list; 46, identifier:logger; 47, identifier:info; 48, string; 49, identifier:outputDir; 50, string; 51, identifier:outputDir; 52, string; 53, identifier:outputDir; 54, string; 55, identifier:outputDir; 56, string; 57, identifier:MSBWTGen; 58, identifier:clearAuxiliaryData; 59, identifier:outputDir; 60, identifier:bamFNs; 61, identifier:seqFN; 62, identifier:offsetFN; 63, identifier:abtFN; 64, identifier:areUniform; 65, identifier:logger; 66, identifier:MSBWTGen; 67, identifier:createFromSeqs; 68, identifier:seqFN; 69, identifier:offsetFN; 70, identifier:bwtFN; 71, identifier:numProcs; 72, identifier:areUniform; 73, identifier:logger; 74, string_content:Saving sorted sequences...; 75, string_content:/seqs.npy; 76, string_content:/offsets.npy; 77, string_content:/about.npy; 78, string_content:/msbwt.npy | 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; 10, 20; 12, 21; 13, 22; 14, 23; 15, 24; 16, 25; 17, 26; 18, 27; 19, 28; 20, 29; 21, 30; 21, 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; 31, 48; 33, 49; 33, 50; 35, 51; 35, 52; 37, 53; 37, 54; 39, 55; 39, 56; 40, 57; 40, 58; 41, 59; 43, 60; 43, 61; 43, 62; 43, 63; 43, 64; 43, 65; 44, 66; 44, 67; 45, 68; 45, 69; 45, 70; 45, 71; 45, 72; 45, 73; 48, 74; 50, 75; 52, 76; 54, 77; 56, 78 | def createMSBWTFromBam(bamFNs, outputDir, numProcs, areUniform, logger):
'''
This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer
@param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME
@param outputDir - the directory for all of the bwt related data
@param numProcs - the number of processes it's allowed to use
@areUniform - true if all the sequences passed into the function are of equal length
'''
#generate the files we will reference and clear out the in memory array before making the BWT
logger.info('Saving sorted sequences...')
seqFN = outputDir+'/seqs.npy'
offsetFN = outputDir+'/offsets.npy'
abtFN = outputDir+'/about.npy'
bwtFN = outputDir+'/msbwt.npy'
MSBWTGen.clearAuxiliaryData(outputDir)
preprocessBams(bamFNs, seqFN, offsetFN, abtFN, areUniform, logger)
MSBWTGen.createFromSeqs(seqFN, offsetFN, bwtFN, numProcs, areUniform, logger) |
0, module; 1, function_definition; 2, function_name:append_responder; 3, parameters; 4, block; 5, identifier:self; 6, identifier:matcher; 7, list_splat_pattern; 8, dictionary_splat_pattern; 9, expression_statement; 10, return_statement; 11, identifier:args; 12, identifier:kwargs; 13, comment:"""Add a responder of last resort.
Like `.autoresponds`, but instead of adding a responder to the top of
the stack, add it to the bottom. This responder will be called if no
others match.
"""; 14, call; 15, attribute; 16, argument_list; 17, identifier:self; 18, identifier:_insert_responder; 19, string:"bottom"; 20, identifier:matcher; 21, list_splat; 22, dictionary_splat; 23, identifier:args; 24, identifier:kwargs | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 10, 14; 14, 15; 14, 16; 15, 17; 15, 18; 16, 19; 16, 20; 16, 21; 16, 22; 21, 23; 22, 24 | def append_responder(self, matcher, *args, **kwargs):
"""Add a responder of last resort.
Like `.autoresponds`, but instead of adding a responder to the top of
the stack, add it to the bottom. This responder will be called if no
others match.
"""
return self._insert_responder("bottom", matcher, *args, **kwargs) |
0, module; 1, function_definition; 2, function_name:unique_list_dicts; 3, parameters; 4, block; 5, identifier:dlist; 6, identifier:key; 7, expression_statement; 8, return_statement; 9, comment:"""Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list:
"""; 10, call; 11, identifier:list; 12, argument_list; 13, call; 14, attribute; 15, argument_list; 16, call; 17, identifier:values; 18, identifier:dict; 19, generator_expression; 20, tuple; 21, for_in_clause; 22, subscript; 23, identifier:val; 24, identifier:val; 25, identifier:dlist; 26, identifier:val; 27, identifier:key | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 7, 9; 8, 10; 10, 11; 10, 12; 12, 13; 13, 14; 13, 15; 14, 16; 14, 17; 16, 18; 16, 19; 19, 20; 19, 21; 20, 22; 20, 23; 21, 24; 21, 25; 22, 26; 22, 27 | def unique_list_dicts(dlist, key):
"""Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list:
"""
return list(dict((val[key], val) for val in dlist).values()) |
0, module; 1, function_definition; 2, function_name:_get_bmu; 3, parameters; 4, block; 5, identifier:self; 6, identifier:activations; 7, expression_statement; 8, comment:# If the neural gas is a recursive neural gas, we need reverse argsort.; 9, if_statement; 10, expression_statement; 11, return_statement; 12, comment:"""Get indices of bmus, sorted by their distance from input."""; 13, comparison_operator:self.argfunc == 'argmax'; 14, block; 15, assignment; 16, call; 17, attribute; 18, string; 19, expression_statement; 20, identifier:sort; 21, call; 22, attribute; 23, argument_list; 24, identifier:self; 25, identifier:argfunc; 26, string_content:argmax; 27, assignment; 28, attribute; 29, argument_list; 30, identifier:sort; 31, identifier:argsort; 32, identifier:activations; 33, unary_operator; 34, identifier:np; 35, identifier:argsort; 36, identifier:activations; 37, integer:1; 38, identifier:activations | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 7, 12; 9, 13; 9, 14; 10, 15; 11, 16; 13, 17; 13, 18; 14, 19; 15, 20; 15, 21; 16, 22; 16, 23; 17, 24; 17, 25; 18, 26; 19, 27; 21, 28; 21, 29; 22, 30; 22, 31; 27, 32; 27, 33; 28, 34; 28, 35; 29, 36; 29, 37; 33, 38 | def _get_bmu(self, activations):
"""Get indices of bmus, sorted by their distance from input."""
# If the neural gas is a recursive neural gas, we need reverse argsort.
if self.argfunc == 'argmax':
activations = -activations
sort = np.argsort(activations, 1)
return sort.argsort() |
0, module; 1, function_definition; 2, function_name:sort_versions; 3, parameters; 4, block; 5, default_parameter; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, expression_statement; 11, function_definition; 12, expression_statement; 13, expression_statement; 14, for_statement; 15, comment:# replace letters found by a negative number; 16, expression_statement; 17, expression_statement; 18, if_statement; 19, comment:# Complete with zeros based on longest item and replace alphas with number; 20, expression_statement; 21, for_statement; 22, expression_statement; 23, return_statement; 24, identifier:versions; 25, tuple; 26, identifier:reverse; 27, False; 28, identifier:sep; 29, string; 30, comment:"""Sort a list of version number strings.
This function ensures that the package sorting based on number name is
performed correctly when including alpha, dev rc1 etc...
"""; 31, comparison_operator:versions == []; 32, block; 33, assignment; 34, function_name:toint; 35, parameters; 36, block; 37, assignment; 38, assignment; 39, identifier:item; 40, identifier:versions; 41, block; 42, assignment; 43, assignment; 44, call; 45, block; 46, assignment; 47, identifier:i; 48, call; 49, block; 50, assignment; 51, list_comprehension; 52, string_content:.; 53, identifier:versions; 54, list; 55, return_statement; 56, identifier:digits; 57, string; 58, identifier:x; 59, try_statement; 60, return_statement; 61, identifier:versions; 62, call; 63, pattern_list; 64, expression_list; 65, expression_statement; 66, expression_statement; 67, for_statement; 68, expression_statement; 69, expression_statement; 70, identifier:replace_dic; 71, dictionary; 72, identifier:alpha; 73, call; 74, identifier:len; 75, argument_list; 76, expression_statement; 77, identifier:nmax; 78, call; 79, identifier:range; 80, argument_list; 81, expression_statement; 82, for_statement; 83, expression_statement; 84, expression_statement; 85, expression_statement; 86, expression_statement; 87, identifier:new_versions; 88, call; 89, subscript; 90, for_in_clause; 91, list; 92, string_content:0123456789; 93, block; 94, except_clause; 95, identifier:n; 96, identifier:list; 97, argument_list; 98, identifier:new_versions; 99, identifier:alpha; 100, identifier:sizes; 101, list; 102, call; 103, call; 104, assignment; 105, assignment; 106, identifier:i; 107, identifier:it; 108, block; 109, call; 110, call; 111, identifier:sorted; 112, argument_list; 113, identifier:alpha; 114, assignment; 115, identifier:max; 116, argument_list; 117, call; 118, assignment; 119, identifier:z; 120, subscript; 121, block; 122, assignment; 123, augmented_assignment; 124, augmented_assignment; 125, assignment; 126, identifier:sorted; 127, argument_list; 128, identifier:n; 129, unary_operator; 130, identifier:n; 131, identifier:new_versions; 132, expression_statement; 133, block; 134, identifier:versions; 135, identifier:set; 136, argument_list; 137, identifier:set; 138, argument_list; 139, identifier:it; 140, call; 141, identifier:temp; 142, list; 143, expression_statement; 144, if_statement; 145, expression_statement; 146, attribute; 147, argument_list; 148, attribute; 149, argument_list; 150, identifier:alpha; 151, keyword_argument; 152, identifier:replace_dic; 153, call; 154, identifier:sizes; 155, identifier:len; 156, argument_list; 157, identifier:item; 158, list; 159, identifier:new_versions; 160, identifier:i; 161, if_statement; 162, identifier:nzeros; 163, binary_operator:nmax - len(item); 164, identifier:item; 165, binary_operator:[0]*nzeros; 166, identifier:item; 167, list; 168, subscript; 169, identifier:item; 170, identifier:new_versions; 171, keyword_argument; 172, integer:1; 173, assignment; 174, expression_statement; 175, attribute; 176, argument_list; 177, assignment; 178, not_operator; 179, block; 180, else_clause; 181, augmented_assignment; 182, identifier:sizes; 183, identifier:add; 184, call; 185, identifier:new_versions; 186, identifier:append; 187, identifier:temp; 188, identifier:reverse; 189, True; 190, identifier:dict; 191, argument_list; 192, identifier:new_versions; 193, comparison_operator:z in replace_dic; 194, block; 195, else_clause; 196, identifier:nmax; 197, call; 198, list; 199, identifier:nzeros; 200, subscript; 201, identifier:new_versions; 202, identifier:i; 203, identifier:reverse; 204, identifier:reverse; 205, identifier:n; 206, call; 207, assignment; 208, identifier:item; 209, identifier:split; 210, identifier:sep; 211, identifier:x; 212, call; 213, call; 214, expression_statement; 215, expression_statement; 216, expression_statement; 217, expression_statement; 218, expression_statement; 219, expression_statement; 220, while_statement; 221, for_statement; 222, block; 223, identifier:temp; 224, identifier:res; 225, identifier:len; 226, argument_list; 227, call; 228, identifier:z; 229, identifier:replace_dic; 230, expression_statement; 231, block; 232, identifier:len; 233, argument_list; 234, integer:0; 235, identifier:versions; 236, identifier:i; 237, identifier:int; 238, argument_list; 239, identifier:n; 240, identifier:x; 241, identifier:toint; 242, argument_list; 243, identifier:isinstance; 244, argument_list; 245, assignment; 246, assignment; 247, assignment; 248, assignment; 249, assignment; 250, assignment; 251, comparison_operator:u'' in res; 252, block; 253, identifier:r; 254, identifier:res; 255, block; 256, expression_statement; 257, identifier:temp; 258, identifier:zip; 259, argument_list; 260, call; 261, expression_statement; 262, identifier:item; 263, identifier:x; 264, identifier:i; 265, identifier:x; 266, identifier:int; 267, identifier:x; 268, call; 269, identifier:middle; 270, call; 271, identifier:tail; 272, call; 273, identifier:head; 274, call; 275, identifier:middle; 276, call; 277, identifier:res; 278, list; 279, string; 280, identifier:res; 281, expression_statement; 282, if_statement; 283, assignment; 284, identifier:alpha; 285, call; 286, attribute; 287, argument_list; 288, call; 289, identifier:u; 290, argument_list; 291, attribute; 292, argument_list; 293, identifier:toint; 294, argument_list; 295, identifier:toint; 296, argument_list; 297, identifier:toint; 298, argument_list; 299, identifier:head; 300, identifier:middle; 301, identifier:tail; 302, call; 303, call; 304, block; 305, identifier:res; 306, list; 307, identifier:list; 308, argument_list; 309, identifier:item; 310, identifier:append; 311, subscript; 312, attribute; 313, argument_list; 314, identifier:x; 315, call; 316, identifier:rstrip; 317, identifier:digits; 318, call; 319, call; 320, identifier:middle; 321, attribute; 322, argument_list; 323, identifier:is_unicode; 324, argument_list; 325, expression_statement; 326, identifier:x; 327, call; 328, identifier:replace_dic; 329, identifier:z; 330, identifier:item; 331, identifier:append; 332, identifier:z; 333, attribute; 334, argument_list; 335, attribute; 336, argument_list; 337, attribute; 338, argument_list; 339, identifier:res; 340, identifier:remove; 341, string; 342, identifier:r; 343, call; 344, identifier:range; 345, argument_list; 346, identifier:x; 347, identifier:lstrip; 348, identifier:digits; 349, call; 350, identifier:replace; 351, identifier:middle; 352, string; 353, call; 354, identifier:replace; 355, identifier:middle; 356, string; 357, attribute; 358, argument_list; 359, unary_operator; 360, unary_operator; 361, unary_operator; 362, attribute; 363, argument_list; 364, attribute; 365, argument_list; 366, identifier:alpha; 367, identifier:add; 368, identifier:r; 369, integer:1; 370, parenthesized_expression; 371, integer:1; 372, identifier:x; 373, identifier:lstrip; 374, identifier:digits; 375, identifier:x; 376, identifier:rstrip; 377, identifier:digits; 378, binary_operator:len(alpha)+1; 379, call; 380, integer:1; 381, identifier:len; 382, argument_list; 383, identifier:alpha | 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; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 5, 24; 5, 25; 6, 26; 6, 27; 7, 28; 7, 29; 8, 30; 9, 31; 9, 32; 10, 33; 11, 34; 11, 35; 11, 36; 12, 37; 13, 38; 14, 39; 14, 40; 14, 41; 16, 42; 17, 43; 18, 44; 18, 45; 20, 46; 21, 47; 21, 48; 21, 49; 22, 50; 23, 51; 29, 52; 31, 53; 31, 54; 32, 55; 33, 56; 33, 57; 35, 58; 36, 59; 36, 60; 37, 61; 37, 62; 38, 63; 38, 64; 41, 65; 41, 66; 41, 67; 41, 68; 41, 69; 42, 70; 42, 71; 43, 72; 43, 73; 44, 74; 44, 75; 45, 76; 46, 77; 46, 78; 48, 79; 48, 80; 49, 81; 49, 82; 49, 83; 49, 84; 49, 85; 49, 86; 50, 87; 50, 88; 51, 89; 51, 90; 55, 91; 57, 92; 59, 93; 59, 94; 60, 95; 62, 96; 62, 97; 63, 98; 63, 99; 63, 100; 64, 101; 64, 102; 64, 103; 65, 104; 66, 105; 67, 106; 67, 107; 67, 108; 68, 109; 69, 110; 73, 111; 73, 112; 75, 113; 76, 114; 78, 115; 78, 116; 80, 117; 81, 118; 82, 119; 82, 120; 82, 121; 83, 122; 84, 123; 85, 124; 86, 125; 88, 126; 88, 127; 89, 128; 89, 129; 90, 130; 90, 131; 93, 132; 94, 133; 97, 134; 102, 135; 102, 136; 103, 137; 103, 138; 104, 139; 104, 140; 105, 141; 105, 142; 108, 143; 108, 144; 108, 145; 109, 146; 109, 147; 110, 148; 110, 149; 112, 150; 112, 151; 114, 152; 114, 153; 116, 154; 117, 155; 117, 156; 118, 157; 118, 158; 120, 159; 120, 160; 121, 161; 122, 162; 122, 163; 123, 164; 123, 165; 124, 166; 124, 167; 125, 168; 125, 169; 127, 170; 127, 171; 129, 172; 132, 173; 133, 174; 140, 175; 140, 176; 143, 177; 144, 178; 144, 179; 144, 180; 145, 181; 146, 182; 146, 183; 147, 184; 148, 185; 148, 186; 149, 187; 151, 188; 151, 189; 153, 190; 153, 191; 156, 192; 161, 193; 161, 194; 161, 195; 163, 196; 163, 197; 165, 198; 165, 199; 167, 200; 168, 201; 168, 202; 171, 203; 171, 204; 173, 205; 173, 206; 174, 207; 175, 208; 175, 209; 176, 210; 177, 211; 177, 212; 178, 213; 179, 214; 179, 215; 179, 216; 179, 217; 179, 218; 179, 219; 179, 220; 179, 221; 180, 222; 181, 223; 181, 224; 184, 225; 184, 226; 191, 227; 193, 228; 193, 229; 194, 230; 195, 231; 197, 232; 197, 233; 198, 234; 200, 235; 200, 236; 206, 237; 206, 238; 207, 239; 207, 240; 212, 241; 212, 242; 213, 243; 213, 244; 214, 245; 215, 246; 216, 247; 217, 248; 218, 249; 219, 250; 220, 251; 220, 252; 221, 253; 221, 254; 221, 255; 222, 256; 226, 257; 227, 258; 227, 259; 230, 260; 231, 261; 233, 262; 238, 263; 242, 264; 244, 265; 244, 266; 245, 267; 245, 268; 246, 269; 246, 270; 247, 271; 247, 272; 248, 273; 248, 274; 249, 275; 249, 276; 250, 277; 250, 278; 251, 279; 251, 280; 252, 281; 255, 282; 256, 283; 259, 284; 259, 285; 260, 286; 260, 287; 261, 288; 268, 289; 268, 290; 270, 291; 270, 292; 272, 293; 272, 294; 274, 295; 274, 296; 276, 297; 276, 298; 278, 299; 278, 300; 278, 301; 281, 302; 282, 303; 282, 304; 283, 305; 283, 306; 285, 307; 285, 308; 286, 309; 286, 310; 287, 311; 288, 312; 288, 313; 290, 314; 291, 315; 291, 316; 292, 317; 294, 318; 296, 319; 298, 320; 302, 321; 302, 322; 303, 323; 303, 324; 304, 325; 306, 326; 308, 327; 311, 328; 311, 329; 312, 330; 312, 331; 313, 332; 315, 333; 315, 334; 318, 335; 318, 336; 319, 337; 319, 338; 321, 339; 321, 340; 322, 341; 324, 342; 325, 343; 327, 344; 327, 345; 333, 346; 333, 347; 334, 348; 335, 349; 335, 350; 336, 351; 336, 352; 337, 353; 337, 354; 338, 355; 338, 356; 343, 357; 343, 358; 345, 359; 345, 360; 345, 361; 349, 362; 349, 363; 353, 364; 353, 365; 357, 366; 357, 367; 358, 368; 359, 369; 360, 370; 361, 371; 362, 372; 362, 373; 363, 374; 364, 375; 364, 376; 365, 377; 370, 378; 378, 379; 378, 380; 379, 381; 379, 382; 382, 383 | def sort_versions(versions=(), reverse=False, sep=u'.'):
"""Sort a list of version number strings.
This function ensures that the package sorting based on number name is
performed correctly when including alpha, dev rc1 etc...
"""
if versions == []:
return []
digits = u'0123456789'
def toint(x):
try:
n = int(x)
except:
n = x
return n
versions = list(versions)
new_versions, alpha, sizes = [], set(), set()
for item in versions:
it = item.split(sep)
temp = []
for i in it:
x = toint(i)
if not isinstance(x, int):
x = u(x)
middle = x.lstrip(digits).rstrip(digits)
tail = toint(x.lstrip(digits).replace(middle, u''))
head = toint(x.rstrip(digits).replace(middle, u''))
middle = toint(middle)
res = [head, middle, tail]
while u'' in res:
res.remove(u'')
for r in res:
if is_unicode(r):
alpha.add(r)
else:
res = [x]
temp += res
sizes.add(len(temp))
new_versions.append(temp)
# replace letters found by a negative number
replace_dic = {}
alpha = sorted(alpha, reverse=True)
if len(alpha):
replace_dic = dict(zip(alpha, list(range(-1, -(len(alpha)+1), -1))))
# Complete with zeros based on longest item and replace alphas with number
nmax = max(sizes)
for i in range(len(new_versions)):
item = []
for z in new_versions[i]:
if z in replace_dic:
item.append(replace_dic[z])
else:
item.append(z)
nzeros = nmax - len(item)
item += [0]*nzeros
item += [versions[i]]
new_versions[i] = item
new_versions = sorted(new_versions, reverse=reverse)
return [n[-1] for n in new_versions] |
0, module; 1, function_definition; 2, function_name:make_qq_plot; 3, parameters; 4, block; 5, identifier:kev; 6, identifier:obs; 7, identifier:mdl; 8, identifier:unit; 9, identifier:key_text; 10, expression_statement; 11, import_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, comment:# HACK: this range of numbers is chosen to give reasonable sampling for my; 22, comment:# sources, which are typically quite soft.; 23, expression_statement; 24, expression_statement; 25, expression_statement; 26, for_statement; 27, expression_statement; 28, expression_statement; 29, return_statement; 30, comment:"""Make a quantile-quantile plot comparing events and a model.
*kev*
A 1D, sorted array of event energy bins measured in keV.
*obs*
A 1D array giving the number or rate of events in each bin.
*mdl*
A 1D array giving the modeled number or rate of events in each bin.
*unit*
Text describing the unit in which *obs* and *mdl* are measured; will
be shown on the plot axes.
*key_text*
Text describing the quantile-quantile comparison quantity; will be
shown on the plot legend.
Returns:
An :class:`omega.RectPlot` instance.
*TODO*: nothing about this is Sherpa-specific. Same goes for some of the
plotting routines in :mod:`pkwit.environments.casa.data`; might be
reasonable to add a submodule for generic X-ray-y plotting routines.
"""; 31, aliased_import; 32, assignment; 33, assignment; 34, assignment; 35, assignment; 36, assignment; 37, assignment; 38, assignment; 39, call; 40, call; 41, assignment; 42, assignment; 43, assignment; 44, identifier:loc; 45, identifier:locs; 46, block; 47, call; 48, assignment; 49, identifier:p; 50, dotted_name; 51, identifier:om; 52, identifier:kev; 53, call; 54, identifier:obs; 55, call; 56, identifier:mdl; 57, call; 58, identifier:c_obs; 59, call; 60, identifier:c_mdl; 61, call; 62, identifier:mx; 63, call; 64, identifier:p; 65, call; 66, attribute; 67, argument_list; 68, attribute; 69, argument_list; 70, identifier:locs; 71, binary_operator:np.array([0, 0.05, 0.08, 0.11, 0.17, 0.3, 0.4, 0.7, 1]) * (kev.size - 2); 72, identifier:c0; 73, binary_operator:mx * 1.05; 74, identifier:c1; 75, binary_operator:mx * 1.1; 76, expression_statement; 77, expression_statement; 78, expression_statement; 79, expression_statement; 80, expression_statement; 81, expression_statement; 82, expression_statement; 83, attribute; 84, argument_list; 85, attribute; 86, float:0.3; 87, identifier:omega; 88, attribute; 89, argument_list; 90, attribute; 91, argument_list; 92, attribute; 93, argument_list; 94, attribute; 95, argument_list; 96, attribute; 97, argument_list; 98, identifier:max; 99, argument_list; 100, attribute; 101, argument_list; 102, identifier:p; 103, identifier:addXY; 104, list; 105, list; 106, string; 107, identifier:p; 108, identifier:addXY; 109, identifier:c_mdl; 110, identifier:c_obs; 111, identifier:key_text; 112, call; 113, parenthesized_expression; 114, identifier:mx; 115, float:1.05; 116, identifier:mx; 117, float:1.1; 118, assignment; 119, assignment; 120, assignment; 121, assignment; 122, assignment; 123, call; 124, call; 125, identifier:p; 126, identifier:setLabels; 127, binary_operator:'Cumulative model ' + unit; 128, binary_operator:'Cumulative data ' + unit; 129, attribute; 130, identifier:vAlign; 131, identifier:np; 132, identifier:asarray; 133, identifier:kev; 134, identifier:np; 135, identifier:asarray; 136, identifier:obs; 137, identifier:np; 138, identifier:asarray; 139, identifier:mdl; 140, identifier:np; 141, identifier:cumsum; 142, identifier:obs; 143, identifier:np; 144, identifier:cumsum; 145, identifier:mdl; 146, subscript; 147, subscript; 148, identifier:om; 149, identifier:RectPlot; 150, integer:0; 151, identifier:mx; 152, integer:0; 153, identifier:mx; 154, string_content:1:1; 155, attribute; 156, argument_list; 157, binary_operator:kev.size - 2; 158, identifier:i0; 159, call; 160, identifier:frac; 161, binary_operator:loc - i0; 162, identifier:kevval; 163, binary_operator:(1 - frac) * kev[i0] + frac * kev[i0+1]; 164, identifier:mdlval; 165, binary_operator:(1 - frac) * c_mdl[i0] + frac * c_mdl[i0+1]; 166, identifier:obsval; 167, binary_operator:(1 - frac) * c_obs[i0] + frac * c_obs[i0+1]; 168, attribute; 169, argument_list; 170, attribute; 171, argument_list; 172, string; 173, identifier:unit; 174, string; 175, identifier:unit; 176, identifier:p; 177, identifier:defaultKeyOverlay; 178, identifier:c_obs; 179, unary_operator; 180, identifier:c_mdl; 181, unary_operator; 182, identifier:np; 183, identifier:array; 184, list; 185, attribute; 186, integer:2; 187, identifier:int; 188, argument_list; 189, identifier:loc; 190, identifier:i0; 191, binary_operator:(1 - frac) * kev[i0]; 192, binary_operator:frac * kev[i0+1]; 193, binary_operator:(1 - frac) * c_mdl[i0]; 194, binary_operator:frac * c_mdl[i0+1]; 195, binary_operator:(1 - frac) * c_obs[i0]; 196, binary_operator:frac * c_obs[i0+1]; 197, identifier:p; 198, identifier:addXY; 199, list; 200, list; 201, binary_operator:'%.2f keV' % kevval; 202, keyword_argument; 203, identifier:p; 204, identifier:addXY; 205, list; 206, list; 207, None; 208, keyword_argument; 209, string_content:Cumulative model; 210, string_content:Cumulative data; 211, integer:1; 212, integer:1; 213, integer:0; 214, float:0.05; 215, float:0.08; 216, float:0.11; 217, float:0.17; 218, float:0.3; 219, float:0.4; 220, float:0.7; 221, integer:1; 222, identifier:kev; 223, identifier:size; 224, call; 225, parenthesized_expression; 226, subscript; 227, identifier:frac; 228, subscript; 229, parenthesized_expression; 230, subscript; 231, identifier:frac; 232, subscript; 233, parenthesized_expression; 234, subscript; 235, identifier:frac; 236, subscript; 237, identifier:mdlval; 238, identifier:mdlval; 239, identifier:c0; 240, identifier:c1; 241, string; 242, identifier:kevval; 243, identifier:dsn; 244, integer:2; 245, identifier:c0; 246, identifier:c1; 247, identifier:obsval; 248, identifier:obsval; 249, identifier:dsn; 250, integer:2; 251, attribute; 252, argument_list; 253, binary_operator:1 - frac; 254, identifier:kev; 255, identifier:i0; 256, identifier:kev; 257, binary_operator:i0+1; 258, binary_operator:1 - frac; 259, identifier:c_mdl; 260, identifier:i0; 261, identifier:c_mdl; 262, binary_operator:i0+1; 263, binary_operator:1 - frac; 264, identifier:c_obs; 265, identifier:i0; 266, identifier:c_obs; 267, binary_operator:i0+1; 268, string_content:%.2f keV; 269, identifier:np; 270, identifier:floor; 271, identifier:loc; 272, integer:1; 273, identifier:frac; 274, identifier:i0; 275, integer:1; 276, integer:1; 277, identifier:frac; 278, identifier:i0; 279, integer:1; 280, integer:1; 281, identifier:frac; 282, identifier:i0; 283, integer:1 | 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; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 10, 30; 11, 31; 12, 32; 13, 33; 14, 34; 15, 35; 16, 36; 17, 37; 18, 38; 19, 39; 20, 40; 23, 41; 24, 42; 25, 43; 26, 44; 26, 45; 26, 46; 27, 47; 28, 48; 29, 49; 31, 50; 31, 51; 32, 52; 32, 53; 33, 54; 33, 55; 34, 56; 34, 57; 35, 58; 35, 59; 36, 60; 36, 61; 37, 62; 37, 63; 38, 64; 38, 65; 39, 66; 39, 67; 40, 68; 40, 69; 41, 70; 41, 71; 42, 72; 42, 73; 43, 74; 43, 75; 46, 76; 46, 77; 46, 78; 46, 79; 46, 80; 46, 81; 46, 82; 47, 83; 47, 84; 48, 85; 48, 86; 50, 87; 53, 88; 53, 89; 55, 90; 55, 91; 57, 92; 57, 93; 59, 94; 59, 95; 61, 96; 61, 97; 63, 98; 63, 99; 65, 100; 65, 101; 66, 102; 66, 103; 67, 104; 67, 105; 67, 106; 68, 107; 68, 108; 69, 109; 69, 110; 69, 111; 71, 112; 71, 113; 73, 114; 73, 115; 75, 116; 75, 117; 76, 118; 77, 119; 78, 120; 79, 121; 80, 122; 81, 123; 82, 124; 83, 125; 83, 126; 84, 127; 84, 128; 85, 129; 85, 130; 88, 131; 88, 132; 89, 133; 90, 134; 90, 135; 91, 136; 92, 137; 92, 138; 93, 139; 94, 140; 94, 141; 95, 142; 96, 143; 96, 144; 97, 145; 99, 146; 99, 147; 100, 148; 100, 149; 104, 150; 104, 151; 105, 152; 105, 153; 106, 154; 112, 155; 112, 156; 113, 157; 118, 158; 118, 159; 119, 160; 119, 161; 120, 162; 120, 163; 121, 164; 121, 165; 122, 166; 122, 167; 123, 168; 123, 169; 124, 170; 124, 171; 127, 172; 127, 173; 128, 174; 128, 175; 129, 176; 129, 177; 146, 178; 146, 179; 147, 180; 147, 181; 155, 182; 155, 183; 156, 184; 157, 185; 157, 186; 159, 187; 159, 188; 161, 189; 161, 190; 163, 191; 163, 192; 165, 193; 165, 194; 167, 195; 167, 196; 168, 197; 168, 198; 169, 199; 169, 200; 169, 201; 169, 202; 170, 203; 170, 204; 171, 205; 171, 206; 171, 207; 171, 208; 172, 209; 174, 210; 179, 211; 181, 212; 184, 213; 184, 214; 184, 215; 184, 216; 184, 217; 184, 218; 184, 219; 184, 220; 184, 221; 185, 222; 185, 223; 188, 224; 191, 225; 191, 226; 192, 227; 192, 228; 193, 229; 193, 230; 194, 231; 194, 232; 195, 233; 195, 234; 196, 235; 196, 236; 199, 237; 199, 238; 200, 239; 200, 240; 201, 241; 201, 242; 202, 243; 202, 244; 205, 245; 205, 246; 206, 247; 206, 248; 208, 249; 208, 250; 224, 251; 224, 252; 225, 253; 226, 254; 226, 255; 228, 256; 228, 257; 229, 258; 230, 259; 230, 260; 232, 261; 232, 262; 233, 263; 234, 264; 234, 265; 236, 266; 236, 267; 241, 268; 251, 269; 251, 270; 252, 271; 253, 272; 253, 273; 257, 274; 257, 275; 258, 276; 258, 277; 262, 278; 262, 279; 263, 280; 263, 281; 267, 282; 267, 283 | def make_qq_plot(kev, obs, mdl, unit, key_text):
"""Make a quantile-quantile plot comparing events and a model.
*kev*
A 1D, sorted array of event energy bins measured in keV.
*obs*
A 1D array giving the number or rate of events in each bin.
*mdl*
A 1D array giving the modeled number or rate of events in each bin.
*unit*
Text describing the unit in which *obs* and *mdl* are measured; will
be shown on the plot axes.
*key_text*
Text describing the quantile-quantile comparison quantity; will be
shown on the plot legend.
Returns:
An :class:`omega.RectPlot` instance.
*TODO*: nothing about this is Sherpa-specific. Same goes for some of the
plotting routines in :mod:`pkwit.environments.casa.data`; might be
reasonable to add a submodule for generic X-ray-y plotting routines.
"""
import omega as om
kev = np.asarray(kev)
obs = np.asarray(obs)
mdl = np.asarray(mdl)
c_obs = np.cumsum(obs)
c_mdl = np.cumsum(mdl)
mx = max(c_obs[-1], c_mdl[-1])
p = om.RectPlot()
p.addXY([0, mx], [0, mx], '1:1')
p.addXY(c_mdl, c_obs, key_text)
# HACK: this range of numbers is chosen to give reasonable sampling for my
# sources, which are typically quite soft.
locs = np.array([0, 0.05, 0.08, 0.11, 0.17, 0.3, 0.4, 0.7, 1]) * (kev.size - 2)
c0 = mx * 1.05
c1 = mx * 1.1
for loc in locs:
i0 = int(np.floor(loc))
frac = loc - i0
kevval = (1 - frac) * kev[i0] + frac * kev[i0+1]
mdlval = (1 - frac) * c_mdl[i0] + frac * c_mdl[i0+1]
obsval = (1 - frac) * c_obs[i0] + frac * c_obs[i0+1]
p.addXY([mdlval, mdlval], [c0, c1], '%.2f keV' % kevval, dsn=2)
p.addXY([c0, c1], [obsval, obsval], None, dsn=2)
p.setLabels('Cumulative model ' + unit, 'Cumulative data ' + unit)
p.defaultKeyOverlay.vAlign = 0.3
return p |
0, module; 1, function_definition; 2, function_name:_qr_factor_full; 3, parameters; 4, block; 5, identifier:a; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, comment:# Compute the packed Q and R matrix information.; 10, expression_statement; 11, comment:# Now we unpack. Start with the R matrix, which is easy: we just; 12, comment:# have to piece it together from the strict lower triangle of 'a'; 13, comment:# and the diagonal in 'rdiag'.; 14, expression_statement; 15, for_statement; 16, comment:# Now the Q matrix. It is the concatenation of n Householder; 17, comment:# transformations, each of which is defined by a row in the upper; 18, comment:# trapezoidal portion of 'a'. We extract the appropriate vector,; 19, comment:# construct the matrix for the Householder transform, and build up; 20, comment:# the Q matrix.; 21, expression_statement; 22, expression_statement; 23, for_statement; 24, return_statement; 25, identifier:dtype; 26, attribute; 27, comment:"""Compute the QR factorization of a matrix, with pivoting.
Parameters:
a - An n-by-m arraylike, m >= n.
dtype - (optional) The data type to use for computations.
Default is np.float.
Returns:
q - An m-by-m orthogonal matrix (q q^T = ident)
r - An n-by-m upper triangular matrix
pmut - An n-element permutation vector
The returned values will satisfy the equation
np.dot(r, q) == a[:,pmut]
The outputs are computed indirectly via the function
_qr_factor_packed. If you need to compute q and r matrices in
production code, there are faster ways to do it. This function is for
testing _qr_factor_packed.
The permutation vector pmut is a vector of the integers 0 through
n-1. It sorts the rows of 'a' by their norms, so that the
pmut[i]'th row of 'a' has the i'th biggest norm."""; 28, assignment; 29, assignment; 30, assignment; 31, identifier:i; 32, call; 33, block; 34, assignment; 35, assignment; 36, identifier:i; 37, call; 38, block; 39, expression_list; 40, identifier:np; 41, identifier:float; 42, pattern_list; 43, attribute; 44, pattern_list; 45, line_continuation:\; 46, call; 47, identifier:r; 48, call; 49, identifier:range; 50, argument_list; 51, expression_statement; 52, expression_statement; 53, identifier:q; 54, call; 55, identifier:v; 56, call; 57, identifier:range; 58, argument_list; 59, expression_statement; 60, expression_statement; 61, expression_statement; 62, expression_statement; 63, identifier:q; 64, identifier:r; 65, identifier:pmut; 66, identifier:n; 67, identifier:m; 68, identifier:a; 69, identifier:shape; 70, identifier:packed; 71, identifier:pmut; 72, identifier:rdiag; 73, identifier:acnorm; 74, identifier:_manual_qr_factor_packed; 75, argument_list; 76, attribute; 77, argument_list; 78, identifier:n; 79, assignment; 80, assignment; 81, attribute; 82, argument_list; 83, attribute; 84, argument_list; 85, identifier:n; 86, assignment; 87, assignment; 88, assignment; 89, assignment; 90, identifier:a; 91, identifier:dtype; 92, identifier:np; 93, identifier:zeros; 94, tuple; 95, subscript; 96, subscript; 97, subscript; 98, subscript; 99, identifier:np; 100, identifier:eye; 101, identifier:m; 102, identifier:np; 103, identifier:empty; 104, identifier:m; 105, subscript; 106, subscript; 107, subscript; 108, integer:0; 109, identifier:hhm; 110, binary_operator:np.eye(m) - 2 * np.outer(v, v) / np.dot(v, v); 111, identifier:q; 112, call; 113, identifier:n; 114, identifier:m; 115, identifier:r; 116, identifier:i; 117, slice; 118, identifier:packed; 119, identifier:i; 120, slice; 121, identifier:r; 122, identifier:i; 123, identifier:i; 124, identifier:rdiag; 125, identifier:i; 126, identifier:v; 127, slice; 128, identifier:packed; 129, identifier:i; 130, identifier:v; 131, slice; 132, call; 133, binary_operator:2 * np.outer(v, v) / np.dot(v, v); 134, attribute; 135, argument_list; 136, identifier:i; 137, identifier:i; 138, identifier:i; 139, attribute; 140, argument_list; 141, binary_operator:2 * np.outer(v, v); 142, call; 143, identifier:np; 144, identifier:dot; 145, identifier:hhm; 146, identifier:q; 147, identifier:np; 148, identifier:eye; 149, identifier:m; 150, integer:2; 151, call; 152, attribute; 153, argument_list; 154, attribute; 155, argument_list; 156, identifier:np; 157, identifier:dot; 158, identifier:v; 159, identifier:v; 160, identifier:np; 161, identifier:outer; 162, identifier:v; 163, identifier:v | 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; 6, 25; 6, 26; 7, 27; 8, 28; 10, 29; 14, 30; 15, 31; 15, 32; 15, 33; 21, 34; 22, 35; 23, 36; 23, 37; 23, 38; 24, 39; 26, 40; 26, 41; 28, 42; 28, 43; 29, 44; 29, 45; 29, 46; 30, 47; 30, 48; 32, 49; 32, 50; 33, 51; 33, 52; 34, 53; 34, 54; 35, 55; 35, 56; 37, 57; 37, 58; 38, 59; 38, 60; 38, 61; 38, 62; 39, 63; 39, 64; 39, 65; 42, 66; 42, 67; 43, 68; 43, 69; 44, 70; 44, 71; 44, 72; 44, 73; 46, 74; 46, 75; 48, 76; 48, 77; 50, 78; 51, 79; 52, 80; 54, 81; 54, 82; 56, 83; 56, 84; 58, 85; 59, 86; 60, 87; 61, 88; 62, 89; 75, 90; 75, 91; 76, 92; 76, 93; 77, 94; 79, 95; 79, 96; 80, 97; 80, 98; 81, 99; 81, 100; 82, 101; 83, 102; 83, 103; 84, 104; 86, 105; 86, 106; 87, 107; 87, 108; 88, 109; 88, 110; 89, 111; 89, 112; 94, 113; 94, 114; 95, 115; 95, 116; 95, 117; 96, 118; 96, 119; 96, 120; 97, 121; 97, 122; 97, 123; 98, 124; 98, 125; 105, 126; 105, 127; 106, 128; 106, 129; 107, 130; 107, 131; 110, 132; 110, 133; 112, 134; 112, 135; 117, 136; 120, 137; 131, 138; 132, 139; 132, 140; 133, 141; 133, 142; 134, 143; 134, 144; 135, 145; 135, 146; 139, 147; 139, 148; 140, 149; 141, 150; 141, 151; 142, 152; 142, 153; 151, 154; 151, 155; 152, 156; 152, 157; 153, 158; 153, 159; 154, 160; 154, 161; 155, 162; 155, 163 | def _qr_factor_full(a, dtype=np.float):
"""Compute the QR factorization of a matrix, with pivoting.
Parameters:
a - An n-by-m arraylike, m >= n.
dtype - (optional) The data type to use for computations.
Default is np.float.
Returns:
q - An m-by-m orthogonal matrix (q q^T = ident)
r - An n-by-m upper triangular matrix
pmut - An n-element permutation vector
The returned values will satisfy the equation
np.dot(r, q) == a[:,pmut]
The outputs are computed indirectly via the function
_qr_factor_packed. If you need to compute q and r matrices in
production code, there are faster ways to do it. This function is for
testing _qr_factor_packed.
The permutation vector pmut is a vector of the integers 0 through
n-1. It sorts the rows of 'a' by their norms, so that the
pmut[i]'th row of 'a' has the i'th biggest norm."""
n, m = a.shape
# Compute the packed Q and R matrix information.
packed, pmut, rdiag, acnorm = \
_manual_qr_factor_packed(a, dtype)
# Now we unpack. Start with the R matrix, which is easy: we just
# have to piece it together from the strict lower triangle of 'a'
# and the diagonal in 'rdiag'.
r = np.zeros((n, m))
for i in range(n):
r[i,:i] = packed[i,:i]
r[i,i] = rdiag[i]
# Now the Q matrix. It is the concatenation of n Householder
# transformations, each of which is defined by a row in the upper
# trapezoidal portion of 'a'. We extract the appropriate vector,
# construct the matrix for the Householder transform, and build up
# the Q matrix.
q = np.eye(m)
v = np.empty(m)
for i in range(n):
v[:] = packed[i]
v[:i] = 0
hhm = np.eye(m) - 2 * np.outer(v, v) / np.dot(v, v)
q = np.dot(hhm, q)
return q, r, pmut |
0, module; 1, function_definition; 2, function_name:_qrd_solve_full; 3, parameters; 4, block; 5, identifier:a; 6, identifier:b; 7, identifier:ddiag; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, assert_statement; 15, assert_statement; 16, assert_statement; 17, comment:# The computation is straightforward.; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, return_statement; 22, identifier:dtype; 23, attribute; 24, comment:"""Solve the equation A^T x = B, D x = 0.
Parameters:
a - an n-by-m array, m >= n
b - an m-vector
ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.)
Returns:
x - n-vector solving the equation.
s - the n-by-n supplementary matrix s.
pmut - n-element permutation vector defining the permutation matrix P.
The equations are solved in a least-squares sense if the system is
rank-deficient. D is a diagonal matrix and hence only its diagonal is
in fact supplied as an argument. The matrix s is full lower triangular
and solves the equation
P^T (A A^T + D D) P = S^T S (needs transposition?)
where P is the permutation matrix defined by the vector pmut; it puts
the rows of 'a' in order of nonincreasing rank, so that a[pmut]
has its rows sorted that way.
"""; 25, assignment; 26, assignment; 27, assignment; 28, assignment; 29, comparison_operator:m >= n; 30, comparison_operator:b.shape == (m, ); 31, comparison_operator:ddiag.shape == (n, ); 32, assignment; 33, assignment; 34, assignment; 35, expression_list; 36, identifier:np; 37, identifier:float; 38, identifier:a; 39, call; 40, identifier:b; 41, call; 42, identifier:ddiag; 43, call; 44, pattern_list; 45, attribute; 46, identifier:m; 47, identifier:n; 48, attribute; 49, tuple; 50, attribute; 51, tuple; 52, pattern_list; 53, call; 54, identifier:bqt; 55, call; 56, pattern_list; 57, call; 58, identifier:x; 59, identifier:s; 60, identifier:pmut; 61, attribute; 62, argument_list; 63, attribute; 64, argument_list; 65, attribute; 66, argument_list; 67, identifier:n; 68, identifier:m; 69, identifier:a; 70, identifier:shape; 71, identifier:b; 72, identifier:shape; 73, identifier:m; 74, identifier:ddiag; 75, identifier:shape; 76, identifier:n; 77, identifier:q; 78, identifier:r; 79, identifier:pmut; 80, identifier:_qr_factor_full; 81, argument_list; 82, attribute; 83, argument_list; 84, identifier:x; 85, identifier:s; 86, identifier:_manual_qrd_solve; 87, argument_list; 88, identifier:np; 89, identifier:asarray; 90, identifier:a; 91, identifier:dtype; 92, identifier:np; 93, identifier:asarray; 94, identifier:b; 95, identifier:dtype; 96, identifier:np; 97, identifier:asarray; 98, identifier:ddiag; 99, identifier:dtype; 100, identifier:a; 101, identifier:np; 102, identifier:dot; 103, identifier:b; 104, attribute; 105, subscript; 106, identifier:pmut; 107, identifier:ddiag; 108, identifier:bqt; 109, keyword_argument; 110, keyword_argument; 111, identifier:q; 112, identifier:T; 113, identifier:r; 114, slice; 115, slice; 116, identifier:dtype; 117, identifier:dtype; 118, identifier:build_s; 119, True; 120, identifier:n | 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; 8, 22; 8, 23; 9, 24; 10, 25; 11, 26; 12, 27; 13, 28; 14, 29; 15, 30; 16, 31; 18, 32; 19, 33; 20, 34; 21, 35; 23, 36; 23, 37; 25, 38; 25, 39; 26, 40; 26, 41; 27, 42; 27, 43; 28, 44; 28, 45; 29, 46; 29, 47; 30, 48; 30, 49; 31, 50; 31, 51; 32, 52; 32, 53; 33, 54; 33, 55; 34, 56; 34, 57; 35, 58; 35, 59; 35, 60; 39, 61; 39, 62; 41, 63; 41, 64; 43, 65; 43, 66; 44, 67; 44, 68; 45, 69; 45, 70; 48, 71; 48, 72; 49, 73; 50, 74; 50, 75; 51, 76; 52, 77; 52, 78; 52, 79; 53, 80; 53, 81; 55, 82; 55, 83; 56, 84; 56, 85; 57, 86; 57, 87; 61, 88; 61, 89; 62, 90; 62, 91; 63, 92; 63, 93; 64, 94; 64, 95; 65, 96; 65, 97; 66, 98; 66, 99; 81, 100; 82, 101; 82, 102; 83, 103; 83, 104; 87, 105; 87, 106; 87, 107; 87, 108; 87, 109; 87, 110; 104, 111; 104, 112; 105, 113; 105, 114; 105, 115; 109, 116; 109, 117; 110, 118; 110, 119; 115, 120 | def _qrd_solve_full(a, b, ddiag, dtype=np.float):
"""Solve the equation A^T x = B, D x = 0.
Parameters:
a - an n-by-m array, m >= n
b - an m-vector
ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.)
Returns:
x - n-vector solving the equation.
s - the n-by-n supplementary matrix s.
pmut - n-element permutation vector defining the permutation matrix P.
The equations are solved in a least-squares sense if the system is
rank-deficient. D is a diagonal matrix and hence only its diagonal is
in fact supplied as an argument. The matrix s is full lower triangular
and solves the equation
P^T (A A^T + D D) P = S^T S (needs transposition?)
where P is the permutation matrix defined by the vector pmut; it puts
the rows of 'a' in order of nonincreasing rank, so that a[pmut]
has its rows sorted that way.
"""
a = np.asarray(a, dtype)
b = np.asarray(b, dtype)
ddiag = np.asarray(ddiag, dtype)
n, m = a.shape
assert m >= n
assert b.shape == (m, )
assert ddiag.shape == (n, )
# The computation is straightforward.
q, r, pmut = _qr_factor_full(a)
bqt = np.dot(b, q.T)
x, s = _manual_qrd_solve(r[:,:n], pmut, ddiag, bqt,
dtype=dtype, build_s=True)
return x, s, pmut |
0, module; 1, function_definition; 2, function_name:concat; 3, parameters; 4, block; 5, identifier:invises; 6, identifier:outvis; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, for_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, for_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, if_statement; 22, expression_statement; 23, identifier:timesort; 24, False; 25, comment:"""Concatenate visibility measurement sets.
invises (list of str)
Paths to the input measurement sets
outvis (str)
Path to the output measurement set.
timesort (boolean)
If true, sort the output in time after concatenation.
Example::
from pwkit.environments.casa import tasks
tasks.concat(['epoch1.ms', 'epoch2.ms'], 'combined.ms')
"""; 26, assignment; 27, assignment; 28, call; 29, block; 30, identifier:invis; 31, identifier:invises; 32, block; 33, call; 34, call; 35, call; 36, call; 37, identifier:invis; 38, subscript; 39, block; 40, call; 41, call; 42, call; 43, identifier:timesort; 44, block; 45, call; 46, identifier:tb; 47, call; 48, identifier:ms; 49, call; 50, attribute; 51, argument_list; 52, raise_statement; 53, if_statement; 54, attribute; 55, argument_list; 56, attribute; 57, argument_list; 58, attribute; 59, argument_list; 60, attribute; 61, argument_list; 62, identifier:invises; 63, slice; 64, expression_statement; 65, attribute; 66, argument_list; 67, attribute; 68, argument_list; 69, attribute; 70, argument_list; 71, expression_statement; 72, attribute; 73, argument_list; 74, attribute; 75, argument_list; 76, attribute; 77, argument_list; 78, attribute; 79, identifier:exists; 80, identifier:outvis; 81, call; 82, not_operator; 83, block; 84, identifier:tb; 85, identifier:open; 86, call; 87, identifier:tb; 88, identifier:copy; 89, call; 90, keyword_argument; 91, keyword_argument; 92, identifier:tb; 93, identifier:close; 94, identifier:ms; 95, identifier:open; 96, call; 97, keyword_argument; 98, integer:1; 99, call; 100, identifier:ms; 101, identifier:writehistory; 102, keyword_argument; 103, keyword_argument; 104, identifier:ms; 105, identifier:writehistory; 106, keyword_argument; 107, keyword_argument; 108, identifier:ms; 109, identifier:writehistory; 110, keyword_argument; 111, keyword_argument; 112, call; 113, identifier:ms; 114, identifier:close; 115, attribute; 116, identifier:table; 117, attribute; 118, identifier:ms; 119, identifier:os; 120, identifier:path; 121, identifier:RuntimeError; 122, argument_list; 123, call; 124, raise_statement; 125, identifier:b; 126, argument_list; 127, identifier:b; 128, argument_list; 129, identifier:deep; 130, True; 131, identifier:valuecopy; 132, True; 133, identifier:b; 134, argument_list; 135, identifier:nomodify; 136, False; 137, attribute; 138, argument_list; 139, identifier:message; 140, string; 141, identifier:origin; 142, string; 143, identifier:message; 144, call; 145, identifier:origin; 146, string; 147, identifier:message; 148, call; 149, identifier:origin; 150, string; 151, attribute; 152, argument_list; 153, identifier:util; 154, identifier:tools; 155, identifier:util; 156, identifier:tools; 157, binary_operator:'output "%s" already exists' % outvis; 158, attribute; 159, argument_list; 160, call; 161, subscript; 162, identifier:outvis; 163, identifier:outvis; 164, identifier:ms; 165, identifier:concatenate; 166, keyword_argument; 167, keyword_argument; 168, keyword_argument; 169, string_content:taskname=tasklib.concat; 170, string_content:tasklib.concat; 171, identifier:b; 172, argument_list; 173, string_content:tasklib.concat; 174, identifier:b; 175, argument_list; 176, string_content:tasklib.concat; 177, identifier:ms; 178, identifier:timesort; 179, string:'output "%s" already exists'; 180, identifier:outvis; 181, attribute; 182, identifier:isdir; 183, identifier:invis; 184, identifier:RuntimeError; 185, argument_list; 186, identifier:invises; 187, integer:0; 188, identifier:msfile; 189, call; 190, identifier:freqtol; 191, call; 192, identifier:dirtol; 193, call; 194, binary_operator:'vis = ' + ', '.join(invises); 195, binary_operator:'timesort = ' + 'FT'[int(timesort)]; 196, identifier:os; 197, identifier:path; 198, binary_operator:'input "%s" does not exist' % invis; 199, identifier:b; 200, argument_list; 201, identifier:b; 202, argument_list; 203, identifier:b; 204, argument_list; 205, string; 206, call; 207, string; 208, subscript; 209, string:'input "%s" does not exist'; 210, identifier:invis; 211, identifier:invis; 212, identifier:concat_freqtol; 213, identifier:concat_dirtol; 214, string_content:vis =; 215, attribute; 216, argument_list; 217, string_content:timesort =; 218, string; 219, call; 220, string; 221, identifier:join; 222, identifier:invises; 223, string_content:FT; 224, identifier:int; 225, argument_list; 226, string_content:,; 227, identifier:timesort | 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; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 7, 23; 7, 24; 8, 25; 9, 26; 10, 27; 11, 28; 11, 29; 12, 30; 12, 31; 12, 32; 13, 33; 14, 34; 15, 35; 16, 36; 17, 37; 17, 38; 17, 39; 18, 40; 19, 41; 20, 42; 21, 43; 21, 44; 22, 45; 26, 46; 26, 47; 27, 48; 27, 49; 28, 50; 28, 51; 29, 52; 32, 53; 33, 54; 33, 55; 34, 56; 34, 57; 35, 58; 35, 59; 36, 60; 36, 61; 38, 62; 38, 63; 39, 64; 40, 65; 40, 66; 41, 67; 41, 68; 42, 69; 42, 70; 44, 71; 45, 72; 45, 73; 47, 74; 47, 75; 49, 76; 49, 77; 50, 78; 50, 79; 51, 80; 52, 81; 53, 82; 53, 83; 54, 84; 54, 85; 55, 86; 56, 87; 56, 88; 57, 89; 57, 90; 57, 91; 58, 92; 58, 93; 60, 94; 60, 95; 61, 96; 61, 97; 63, 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; 70, 111; 71, 112; 72, 113; 72, 114; 74, 115; 74, 116; 76, 117; 76, 118; 78, 119; 78, 120; 81, 121; 81, 122; 82, 123; 83, 124; 86, 125; 86, 126; 89, 127; 89, 128; 90, 129; 90, 130; 91, 131; 91, 132; 96, 133; 96, 134; 97, 135; 97, 136; 99, 137; 99, 138; 102, 139; 102, 140; 103, 141; 103, 142; 106, 143; 106, 144; 107, 145; 107, 146; 110, 147; 110, 148; 111, 149; 111, 150; 112, 151; 112, 152; 115, 153; 115, 154; 117, 155; 117, 156; 122, 157; 123, 158; 123, 159; 124, 160; 126, 161; 128, 162; 134, 163; 137, 164; 137, 165; 138, 166; 138, 167; 138, 168; 140, 169; 142, 170; 144, 171; 144, 172; 146, 173; 148, 174; 148, 175; 150, 176; 151, 177; 151, 178; 157, 179; 157, 180; 158, 181; 158, 182; 159, 183; 160, 184; 160, 185; 161, 186; 161, 187; 166, 188; 166, 189; 167, 190; 167, 191; 168, 192; 168, 193; 172, 194; 175, 195; 181, 196; 181, 197; 185, 198; 189, 199; 189, 200; 191, 201; 191, 202; 193, 203; 193, 204; 194, 205; 194, 206; 195, 207; 195, 208; 198, 209; 198, 210; 200, 211; 202, 212; 204, 213; 205, 214; 206, 215; 206, 216; 207, 217; 208, 218; 208, 219; 215, 220; 215, 221; 216, 222; 218, 223; 219, 224; 219, 225; 220, 226; 225, 227 | def concat(invises, outvis, timesort=False):
"""Concatenate visibility measurement sets.
invises (list of str)
Paths to the input measurement sets
outvis (str)
Path to the output measurement set.
timesort (boolean)
If true, sort the output in time after concatenation.
Example::
from pwkit.environments.casa import tasks
tasks.concat(['epoch1.ms', 'epoch2.ms'], 'combined.ms')
"""
tb = util.tools.table()
ms = util.tools.ms()
if os.path.exists(outvis):
raise RuntimeError('output "%s" already exists' % outvis)
for invis in invises:
if not os.path.isdir(invis):
raise RuntimeError('input "%s" does not exist' % invis)
tb.open(b(invises[0]))
tb.copy(b(outvis), deep=True, valuecopy=True)
tb.close()
ms.open(b(outvis), nomodify=False)
for invis in invises[1:]:
ms.concatenate(msfile=b(invis), freqtol=b(concat_freqtol),
dirtol=b(concat_dirtol))
ms.writehistory(message=b'taskname=tasklib.concat', origin=b'tasklib.concat')
ms.writehistory(message=b('vis = ' + ', '.join(invises)), origin=b'tasklib.concat')
ms.writehistory(message=b('timesort = ' + 'FT'[int(timesort)]), origin=b'tasklib.concat')
if timesort:
ms.timesort()
ms.close() |
0, module; 1, function_definition; 2, function_name:get_zones_of_account; 3, parameters; 4, block; 5, identifier:self; 6, identifier:account_name; 7, default_parameter; 8, dictionary_splat_pattern; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, identifier:q; 14, None; 15, identifier:kwargs; 16, comment:"""Returns a list of zones for the specified account.
Arguments:
account_name -- The name of the account.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMARY
SECONDARY
ALIAS
sort -- The sort column used to order the list. Valid values for the sort field are:
NAME
ACCOUNT_NAME
RECORD_COUNT
ZONE_TYPE
reverse -- Whether the list is ascending(False) or descending(True)
offset -- The position in the list for the first returned element(0 based)
limit -- The maximum number of rows to be returned.
"""; 17, assignment; 18, assignment; 19, call; 20, identifier:uri; 21, binary_operator:"/v1/accounts/" + account_name + "/zones"; 22, identifier:params; 23, call; 24, attribute; 25, argument_list; 26, binary_operator:"/v1/accounts/" + account_name; 27, string:"/zones"; 28, identifier:build_params; 29, argument_list; 30, attribute; 31, identifier:get; 32, identifier:uri; 33, identifier:params; 34, string:"/v1/accounts/"; 35, identifier:account_name; 36, identifier:q; 37, identifier:kwargs; 38, identifier:self; 39, identifier:rest_api_connection | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 7, 14; 8, 15; 9, 16; 10, 17; 11, 18; 12, 19; 17, 20; 17, 21; 18, 22; 18, 23; 19, 24; 19, 25; 21, 26; 21, 27; 23, 28; 23, 29; 24, 30; 24, 31; 25, 32; 25, 33; 26, 34; 26, 35; 29, 36; 29, 37; 30, 38; 30, 39 | def get_zones_of_account(self, account_name, q=None, **kwargs):
"""Returns a list of zones for the specified account.
Arguments:
account_name -- The name of the account.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMARY
SECONDARY
ALIAS
sort -- The sort column used to order the list. Valid values for the sort field are:
NAME
ACCOUNT_NAME
RECORD_COUNT
ZONE_TYPE
reverse -- Whether the list is ascending(False) or descending(True)
offset -- The position in the list for the first returned element(0 based)
limit -- The maximum number of rows to be returned.
"""
uri = "/v1/accounts/" + account_name + "/zones"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) |
0, module; 1, function_definition; 2, function_name:get_zones; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, dictionary_splat_pattern; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, identifier:q; 13, None; 14, identifier:kwargs; 15, comment:"""Returns a list of zones across all of the user's accounts.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMARY
SECONDARY
ALIAS
sort -- The sort column used to order the list. Valid values for the sort field are:
NAME
ACCOUNT_NAME
RECORD_COUNT
ZONE_TYPE
reverse -- Whether the list is ascending(False) or descending(True)
offset -- The position in the list for the first returned element(0 based)
limit -- The maximum number of rows to be returned.
"""; 16, assignment; 17, assignment; 18, call; 19, identifier:uri; 20, string:"/v1/zones"; 21, identifier:params; 22, call; 23, attribute; 24, argument_list; 25, identifier:build_params; 26, argument_list; 27, attribute; 28, identifier:get; 29, identifier:uri; 30, identifier:params; 31, identifier:q; 32, identifier:kwargs; 33, identifier:self; 34, identifier:rest_api_connection | 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; 9, 16; 10, 17; 11, 18; 16, 19; 16, 20; 17, 21; 17, 22; 18, 23; 18, 24; 22, 25; 22, 26; 23, 27; 23, 28; 24, 29; 24, 30; 26, 31; 26, 32; 27, 33; 27, 34 | def get_zones(self, q=None, **kwargs):
"""Returns a list of zones across all of the user's accounts.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMARY
SECONDARY
ALIAS
sort -- The sort column used to order the list. Valid values for the sort field are:
NAME
ACCOUNT_NAME
RECORD_COUNT
ZONE_TYPE
reverse -- Whether the list is ascending(False) or descending(True)
offset -- The position in the list for the first returned element(0 based)
limit -- The maximum number of rows to be returned.
"""
uri = "/v1/zones"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) |
0, module; 1, function_definition; 2, function_name:get_rrsets; 3, parameters; 4, block; 5, identifier:self; 6, identifier:zone_name; 7, default_parameter; 8, dictionary_splat_pattern; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, identifier:q; 14, None; 15, identifier:kwargs; 16, comment:"""Returns the list of RRSets in the specified zone.
Arguments:
zone_name -- The name of the zone.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
ttl - must match the TTL for the rrset
owner - substring match of the owner name
value - substring match of the first BIND field value
sort -- The sort column used to order the list. Valid values for the sort field are:
OWNER
TTL
TYPE
reverse -- Whether the list is ascending(False) or descending(True)
offset -- The position in the list for the first returned element(0 based)
limit -- The maximum number of rows to be returned.
"""; 17, assignment; 18, assignment; 19, call; 20, identifier:uri; 21, binary_operator:"/v1/zones/" + zone_name + "/rrsets"; 22, identifier:params; 23, call; 24, attribute; 25, argument_list; 26, binary_operator:"/v1/zones/" + zone_name; 27, string:"/rrsets"; 28, identifier:build_params; 29, argument_list; 30, attribute; 31, identifier:get; 32, identifier:uri; 33, identifier:params; 34, string:"/v1/zones/"; 35, identifier:zone_name; 36, identifier:q; 37, identifier:kwargs; 38, identifier:self; 39, identifier:rest_api_connection | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 7, 14; 8, 15; 9, 16; 10, 17; 11, 18; 12, 19; 17, 20; 17, 21; 18, 22; 18, 23; 19, 24; 19, 25; 21, 26; 21, 27; 23, 28; 23, 29; 24, 30; 24, 31; 25, 32; 25, 33; 26, 34; 26, 35; 29, 36; 29, 37; 30, 38; 30, 39 | def get_rrsets(self, zone_name, q=None, **kwargs):
"""Returns the list of RRSets in the specified zone.
Arguments:
zone_name -- The name of the zone.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
ttl - must match the TTL for the rrset
owner - substring match of the owner name
value - substring match of the first BIND field value
sort -- The sort column used to order the list. Valid values for the sort field are:
OWNER
TTL
TYPE
reverse -- Whether the list is ascending(False) or descending(True)
offset -- The position in the list for the first returned element(0 based)
limit -- The maximum number of rows to be returned.
"""
uri = "/v1/zones/" + zone_name + "/rrsets"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) |
0, module; 1, function_definition; 2, function_name:nested_tuple; 3, parameters; 4, block; 5, identifier:container; 6, expression_statement; 7, if_statement; 8, if_statement; 9, if_statement; 10, return_statement; 11, comment:"""Recursively transform a container structure to a nested tuple.
The function understands container types inheriting from the selected abstract base
classes in `collections.abc`, and performs the following replacements:
`Mapping`
`tuple` of key-value pair `tuple`s. The order is preserved in the case of an
`OrderedDict`, otherwise the key-value pairs are sorted if orderable and
otherwise kept in the order of iteration.
`Sequence`
`tuple` containing the same elements in unchanged order.
`Container and Iterable and Sized` (equivalent to `Collection` in python >= 3.6)
`tuple` containing the same elements in sorted order if orderable and otherwise
kept in the order of iteration.
The function recurses into these container types to perform the same replacement,
and leaves objects of other types untouched.
The returned container is hashable if and only if all the values contained in the
original data structure are hashable.
Parameters
----------
container
Data structure to transform into a nested tuple.
Returns
-------
tuple
Nested tuple containing the same data as `container`.
"""; 12, call; 13, block; 14, call; 15, block; 16, not_operator; 17, block; 18, identifier:container; 19, identifier:isinstance; 20, argument_list; 21, return_statement; 22, identifier:isinstance; 23, argument_list; 24, return_statement; 25, call; 26, if_statement; 27, if_statement; 28, identifier:container; 29, identifier:OrderedDict; 30, call; 31, identifier:container; 32, identifier:Mapping; 33, call; 34, identifier:isinstance; 35, argument_list; 36, call; 37, block; 38, parenthesized_expression; 39, block; 40, identifier:tuple; 41, argument_list; 42, identifier:tuple; 43, argument_list; 44, identifier:container; 45, tuple; 46, identifier:isinstance; 47, argument_list; 48, return_statement; 49, boolean_operator; 50, return_statement; 51, call; 52, call; 53, identifier:str; 54, identifier:bytes; 55, identifier:container; 56, identifier:Sequence; 57, call; 58, boolean_operator; 59, call; 60, call; 61, identifier:map; 62, argument_list; 63, identifier:sorted_if_possible; 64, argument_list; 65, identifier:tuple; 66, argument_list; 67, call; 68, call; 69, identifier:isinstance; 70, argument_list; 71, identifier:tuple; 72, argument_list; 73, identifier:nested_tuple; 74, call; 75, call; 76, call; 77, identifier:isinstance; 78, argument_list; 79, identifier:isinstance; 80, argument_list; 81, identifier:container; 82, identifier:Sized; 83, call; 84, attribute; 85, argument_list; 86, identifier:map; 87, argument_list; 88, identifier:map; 89, argument_list; 90, identifier:container; 91, identifier:Container; 92, identifier:container; 93, identifier:Iterable; 94, identifier:sorted_if_possible; 95, argument_list; 96, identifier:container; 97, identifier:items; 98, identifier:nested_tuple; 99, call; 100, identifier:nested_tuple; 101, identifier:container; 102, call; 103, attribute; 104, argument_list; 105, identifier:map; 106, argument_list; 107, identifier:container; 108, identifier:items; 109, identifier:nested_tuple; 110, identifier:container | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 7, 13; 8, 14; 8, 15; 9, 16; 9, 17; 10, 18; 12, 19; 12, 20; 13, 21; 14, 22; 14, 23; 15, 24; 16, 25; 17, 26; 17, 27; 20, 28; 20, 29; 21, 30; 23, 31; 23, 32; 24, 33; 25, 34; 25, 35; 26, 36; 26, 37; 27, 38; 27, 39; 30, 40; 30, 41; 33, 42; 33, 43; 35, 44; 35, 45; 36, 46; 36, 47; 37, 48; 38, 49; 39, 50; 41, 51; 43, 52; 45, 53; 45, 54; 47, 55; 47, 56; 48, 57; 49, 58; 49, 59; 50, 60; 51, 61; 51, 62; 52, 63; 52, 64; 57, 65; 57, 66; 58, 67; 58, 68; 59, 69; 59, 70; 60, 71; 60, 72; 62, 73; 62, 74; 64, 75; 66, 76; 67, 77; 67, 78; 68, 79; 68, 80; 70, 81; 70, 82; 72, 83; 74, 84; 74, 85; 75, 86; 75, 87; 76, 88; 76, 89; 78, 90; 78, 91; 80, 92; 80, 93; 83, 94; 83, 95; 84, 96; 84, 97; 87, 98; 87, 99; 89, 100; 89, 101; 95, 102; 99, 103; 99, 104; 102, 105; 102, 106; 103, 107; 103, 108; 106, 109; 106, 110 | def nested_tuple(container):
"""Recursively transform a container structure to a nested tuple.
The function understands container types inheriting from the selected abstract base
classes in `collections.abc`, and performs the following replacements:
`Mapping`
`tuple` of key-value pair `tuple`s. The order is preserved in the case of an
`OrderedDict`, otherwise the key-value pairs are sorted if orderable and
otherwise kept in the order of iteration.
`Sequence`
`tuple` containing the same elements in unchanged order.
`Container and Iterable and Sized` (equivalent to `Collection` in python >= 3.6)
`tuple` containing the same elements in sorted order if orderable and otherwise
kept in the order of iteration.
The function recurses into these container types to perform the same replacement,
and leaves objects of other types untouched.
The returned container is hashable if and only if all the values contained in the
original data structure are hashable.
Parameters
----------
container
Data structure to transform into a nested tuple.
Returns
-------
tuple
Nested tuple containing the same data as `container`.
"""
if isinstance(container, OrderedDict):
return tuple(map(nested_tuple, container.items()))
if isinstance(container, Mapping):
return tuple(sorted_if_possible(map(nested_tuple, container.items())))
if not isinstance(container, (str, bytes)):
if isinstance(container, Sequence):
return tuple(map(nested_tuple, container))
if (
isinstance(container, Container)
and isinstance(container, Iterable)
and isinstance(container, Sized)
):
return tuple(sorted_if_possible(map(nested_tuple, container)))
return container |
0, module; 1, function_definition; 2, function_name:_ranges_key; 3, parameters; 4, block; 5, identifier:r; 6, identifier:delta_indices; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, comment:"""Sorting key for ranges.
When used with ``reverse=True``, this can be used to sort index ranges into
the order we would prefer to eliminate them by evaluating KroneckerDeltas:
First, eliminate primed indices, then indices names higher in the alphabet.
"""; 11, assignment; 12, comparison_operator:idx in delta_indices; 13, block; 14, else_clause; 15, identifier:idx; 16, attribute; 17, identifier:idx; 18, identifier:delta_indices; 19, return_statement; 20, comment:# ranges that are not in delta_indices should remain in the original; 21, comment:# order; 22, block; 23, identifier:r; 24, identifier:index_symbol; 25, tuple; 26, return_statement; 27, attribute; 28, attribute; 29, tuple; 30, attribute; 31, identifier:primed; 32, attribute; 33, identifier:name; 34, integer:0; 35, string; 36, identifier:r; 37, identifier:index_symbol; 38, identifier:r; 39, identifier:index_symbol; 40, string_content: | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 9, 12; 9, 13; 9, 14; 11, 15; 11, 16; 12, 17; 12, 18; 13, 19; 14, 20; 14, 21; 14, 22; 16, 23; 16, 24; 19, 25; 22, 26; 25, 27; 25, 28; 26, 29; 27, 30; 27, 31; 28, 32; 28, 33; 29, 34; 29, 35; 30, 36; 30, 37; 32, 38; 32, 39; 35, 40 | def _ranges_key(r, delta_indices):
"""Sorting key for ranges.
When used with ``reverse=True``, this can be used to sort index ranges into
the order we would prefer to eliminate them by evaluating KroneckerDeltas:
First, eliminate primed indices, then indices names higher in the alphabet.
"""
idx = r.index_symbol
if idx in delta_indices:
return (r.index_symbol.primed, r.index_symbol.name)
else:
# ranges that are not in delta_indices should remain in the original
# order
return (0, ' ') |
0, module; 1, function_definition; 2, function_name:plot; 3, parameters; 4, block; 5, identifier:self; 6, identifier:x; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, expression_statement; 12, if_statement; 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, expression_statement; 22, if_statement; 23, expression_statement; 24, if_statement; 25, expression_statement; 26, if_statement; 27, expression_statement; 28, expression_statement; 29, expression_statement; 30, identifier:row_order; 31, None; 32, identifier:imshow_kwargs; 33, None; 34, identifier:strip; 35, True; 36, comment:"""
Plot the scaled ChIP-seq data.
:param x: X-axis to use (e.g, for TSS +/- 1kb with 100 bins, this would
be `np.linspace(-1000, 1000, 100)`)
:param row_order: Array-like object containing row order -- typically
the result of an `np.argsort` call.
:param strip: Include axes along the left side with points that can be
clicked to spawn a minibrowser for that feature.
"""; 37, assignment; 38, comparison_operator:row_order is None; 39, block; 40, assignment; 41, assignment; 42, assignment; 43, assignment; 44, identifier:imshow_kwargs; 45, block; 46, comparison_operator:'cmap' not in _imshow_kwargs; 47, block; 48, assignment; 49, call; 50, call; 51, identifier:strip_ax; 52, block; 53, call; 54, identifier:strip_ax; 55, block; 56, call; 57, attribute; 58, block; 59, else_clause; 60, call; 61, assignment; 62, assignment; 63, identifier:nrows; 64, subscript; 65, identifier:row_order; 66, None; 67, expression_statement; 68, identifier:extent; 69, tuple; 70, identifier:axes_info; 71, call; 72, pattern_list; 73, identifier:axes_info; 74, identifier:_imshow_kwargs; 75, call; 76, expression_statement; 77, string; 78, identifier:_imshow_kwargs; 79, expression_statement; 80, identifier:mappable; 81, call; 82, attribute; 83, argument_list; 84, attribute; 85, argument_list; 86, expression_statement; 87, expression_statement; 88, expression_statement; 89, attribute; 90, argument_list; 91, expression_statement; 92, expression_statement; 93, attribute; 94, argument_list; 95, identifier:self; 96, identifier:db; 97, expression_statement; 98, block; 99, attribute; 100, argument_list; 101, attribute; 102, identifier:fig; 103, attribute; 104, dictionary; 105, attribute; 106, integer:0; 107, assignment; 108, call; 109, call; 110, integer:0; 111, identifier:nrows; 112, attribute; 113, argument_list; 114, identifier:fig; 115, identifier:matrix_ax; 116, identifier:line_ax; 117, identifier:strip_ax; 118, identifier:cbar_ax; 119, identifier:dict; 120, argument_list; 121, call; 122, string_content:cmap; 123, assignment; 124, attribute; 125, argument_list; 126, identifier:plt; 127, identifier:colorbar; 128, identifier:mappable; 129, identifier:cbar_ax; 130, identifier:line_ax; 131, identifier:plot; 132, identifier:x; 133, call; 134, assignment; 135, assignment; 136, assignment; 137, identifier:matrix_ax; 138, identifier:axis; 139, string; 140, call; 141, call; 142, attribute; 143, identifier:set_visible; 144, False; 145, assignment; 146, expression_statement; 147, attribute; 148, identifier:mpl_connect; 149, string; 150, attribute; 151, identifier:self; 152, identifier:fig; 153, identifier:self; 154, identifier:axes; 155, pair; 156, pair; 157, pair; 158, pair; 159, attribute; 160, identifier:shape; 161, identifier:row_order; 162, call; 163, identifier:min; 164, argument_list; 165, identifier:max; 166, argument_list; 167, attribute; 168, identifier:matrix_and_line_shell; 169, keyword_argument; 170, keyword_argument; 171, keyword_argument; 172, keyword_argument; 173, attribute; 174, argument_list; 175, subscript; 176, call; 177, identifier:matrix_ax; 178, identifier:imshow; 179, subscript; 180, dictionary_splat; 181, attribute; 182, argument_list; 183, pattern_list; 184, call; 185, attribute; 186, attribute; 187, attribute; 188, identifier:row_order; 189, string_content:tight; 190, attribute; 191, argument_list; 192, attribute; 193, argument_list; 194, identifier:matrix_ax; 195, identifier:xaxis; 196, attribute; 197, call; 198, assignment; 199, identifier:fig; 200, identifier:canvas; 201, string_content:pick_event; 202, identifier:self; 203, identifier:callback; 204, string; 205, identifier:matrix_ax; 206, string; 207, identifier:strip_ax; 208, string; 209, identifier:line_ax; 210, string; 211, identifier:cbar_ax; 212, identifier:self; 213, identifier:diffed_array; 214, attribute; 215, argument_list; 216, identifier:x; 217, identifier:x; 218, identifier:metaseq; 219, identifier:plotutils; 220, identifier:strip; 221, identifier:strip; 222, identifier:aspect; 223, string; 224, identifier:extent; 225, identifier:extent; 226, identifier:interpolation; 227, string; 228, identifier:_imshow_kwargs; 229, identifier:update; 230, identifier:imshow_kwargs; 231, identifier:_imshow_kwargs; 232, string; 233, attribute; 234, argument_list; 235, attribute; 236, identifier:row_order; 237, identifier:_imshow_kwargs; 238, attribute; 239, identifier:mean; 240, keyword_argument; 241, identifier:line; 242, attribute; 243, argument_list; 244, identifier:line; 245, identifier:features; 246, identifier:self; 247, identifier:features; 248, identifier:line; 249, identifier:ind; 250, attribute; 251, identifier:set_visible; 252, False; 253, attribute; 254, identifier:set_visible; 255, False; 256, identifier:self; 257, identifier:minibrowser; 258, identifier:GeneChipseqMiniBrowser; 259, argument_list; 260, attribute; 261, call; 262, string_content:matrix_ax; 263, string_content:strip_ax; 264, string_content:line_ax; 265, string_content:cbar_ax; 266, identifier:np; 267, identifier:arange; 268, identifier:nrows; 269, string_content:auto; 270, string_content:nearest; 271, string_content:cmap; 272, attribute; 273, identifier:smart_colormap; 274, call; 275, call; 276, identifier:self; 277, identifier:diffed_array; 278, identifier:self; 279, identifier:diffed_array; 280, identifier:axis; 281, integer:0; 282, identifier:strip_ax; 283, identifier:plot; 284, call; 285, binary_operator:np.arange(nrows) + 0.5; 286, dictionary_splat; 287, identifier:strip_ax; 288, identifier:xaxis; 289, identifier:matrix_ax; 290, identifier:yaxis; 291, list; 292, keyword_argument; 293, keyword_argument; 294, keyword_argument; 295, identifier:self; 296, identifier:minibrowser; 297, identifier:SignalChipseqMiniBrowser; 298, argument_list; 299, identifier:metaseq; 300, identifier:colormap_adjust; 301, attribute; 302, argument_list; 303, attribute; 304, argument_list; 305, attribute; 306, argument_list; 307, call; 308, float:0.5; 309, attribute; 310, attribute; 311, attribute; 312, identifier:db; 313, attribute; 314, identifier:plotting_kwargs; 315, attribute; 316, identifier:local_coverage_kwargs; 317, attribute; 318, list; 319, keyword_argument; 320, keyword_argument; 321, attribute; 322, identifier:min; 323, attribute; 324, identifier:max; 325, identifier:np; 326, identifier:zeros; 327, tuple; 328, attribute; 329, argument_list; 330, identifier:self; 331, identifier:_strip_kwargs; 332, identifier:self; 333, identifier:ip; 334, identifier:self; 335, identifier:control; 336, identifier:self; 337, identifier:db; 338, identifier:self; 339, identifier:browser_plotting_kwargs; 340, identifier:self; 341, identifier:browser_local_coverage_kwargs; 342, attribute; 343, attribute; 344, identifier:plotting_kwargs; 345, attribute; 346, identifier:local_coverage_kwargs; 347, attribute; 348, identifier:self; 349, identifier:diffed_array; 350, identifier:self; 351, identifier:diffed_array; 352, identifier:nrows; 353, identifier:np; 354, identifier:arange; 355, identifier:nrows; 356, identifier:self; 357, identifier:ip; 358, identifier:self; 359, identifier:control; 360, identifier:self; 361, identifier:browser_plotting_kwargs; 362, identifier:self; 363, identifier:browser_local_coverage_kwargs | 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; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 7, 30; 7, 31; 8, 32; 8, 33; 9, 34; 9, 35; 10, 36; 11, 37; 12, 38; 12, 39; 13, 40; 14, 41; 15, 42; 16, 43; 17, 44; 17, 45; 18, 46; 18, 47; 19, 48; 20, 49; 21, 50; 22, 51; 22, 52; 23, 53; 24, 54; 24, 55; 25, 56; 26, 57; 26, 58; 26, 59; 27, 60; 28, 61; 29, 62; 37, 63; 37, 64; 38, 65; 38, 66; 39, 67; 40, 68; 40, 69; 41, 70; 41, 71; 42, 72; 42, 73; 43, 74; 43, 75; 45, 76; 46, 77; 46, 78; 47, 79; 48, 80; 48, 81; 49, 82; 49, 83; 50, 84; 50, 85; 52, 86; 52, 87; 52, 88; 53, 89; 53, 90; 55, 91; 55, 92; 56, 93; 56, 94; 57, 95; 57, 96; 58, 97; 59, 98; 60, 99; 60, 100; 61, 101; 61, 102; 62, 103; 62, 104; 64, 105; 64, 106; 67, 107; 69, 108; 69, 109; 69, 110; 69, 111; 71, 112; 71, 113; 72, 114; 72, 115; 72, 116; 72, 117; 72, 118; 75, 119; 75, 120; 76, 121; 77, 122; 79, 123; 81, 124; 81, 125; 82, 126; 82, 127; 83, 128; 83, 129; 84, 130; 84, 131; 85, 132; 85, 133; 86, 134; 87, 135; 88, 136; 89, 137; 89, 138; 90, 139; 91, 140; 92, 141; 93, 142; 93, 143; 94, 144; 97, 145; 98, 146; 99, 147; 99, 148; 100, 149; 100, 150; 101, 151; 101, 152; 103, 153; 103, 154; 104, 155; 104, 156; 104, 157; 104, 158; 105, 159; 105, 160; 107, 161; 107, 162; 108, 163; 108, 164; 109, 165; 109, 166; 112, 167; 112, 168; 113, 169; 120, 170; 120, 171; 120, 172; 121, 173; 121, 174; 123, 175; 123, 176; 124, 177; 124, 178; 125, 179; 125, 180; 133, 181; 133, 182; 134, 183; 134, 184; 135, 185; 135, 186; 136, 187; 136, 188; 139, 189; 140, 190; 140, 191; 141, 192; 141, 193; 142, 194; 142, 195; 145, 196; 145, 197; 146, 198; 147, 199; 147, 200; 149, 201; 150, 202; 150, 203; 155, 204; 155, 205; 156, 206; 156, 207; 157, 208; 157, 209; 158, 210; 158, 211; 159, 212; 159, 213; 162, 214; 162, 215; 164, 216; 166, 217; 167, 218; 167, 219; 169, 220; 169, 221; 170, 222; 170, 223; 171, 224; 171, 225; 172, 226; 172, 227; 173, 228; 173, 229; 174, 230; 175, 231; 175, 232; 176, 233; 176, 234; 179, 235; 179, 236; 180, 237; 181, 238; 181, 239; 182, 240; 183, 241; 184, 242; 184, 243; 185, 244; 185, 245; 186, 246; 186, 247; 187, 248; 187, 249; 190, 250; 190, 251; 191, 252; 192, 253; 192, 254; 193, 255; 196, 256; 196, 257; 197, 258; 197, 259; 198, 260; 198, 261; 204, 262; 206, 263; 208, 264; 210, 265; 214, 266; 214, 267; 215, 268; 223, 269; 227, 270; 232, 271; 233, 272; 233, 273; 234, 274; 234, 275; 235, 276; 235, 277; 238, 278; 238, 279; 240, 280; 240, 281; 242, 282; 242, 283; 243, 284; 243, 285; 243, 286; 250, 287; 250, 288; 253, 289; 253, 290; 259, 291; 259, 292; 259, 293; 259, 294; 260, 295; 260, 296; 261, 297; 261, 298; 272, 299; 272, 300; 274, 301; 274, 302; 275, 303; 275, 304; 284, 305; 284, 306; 285, 307; 285, 308; 286, 309; 291, 310; 291, 311; 292, 312; 292, 313; 293, 314; 293, 315; 294, 316; 294, 317; 298, 318; 298, 319; 298, 320; 301, 321; 301, 322; 303, 323; 303, 324; 305, 325; 305, 326; 306, 327; 307, 328; 307, 329; 309, 330; 309, 331; 310, 332; 310, 333; 311, 334; 311, 335; 313, 336; 313, 337; 315, 338; 315, 339; 317, 340; 317, 341; 318, 342; 318, 343; 319, 344; 319, 345; 320, 346; 320, 347; 321, 348; 321, 349; 323, 350; 323, 351; 327, 352; 328, 353; 328, 354; 329, 355; 342, 356; 342, 357; 343, 358; 343, 359; 345, 360; 345, 361; 347, 362; 347, 363 | def plot(self, x, row_order=None, imshow_kwargs=None, strip=True):
"""
Plot the scaled ChIP-seq data.
:param x: X-axis to use (e.g, for TSS +/- 1kb with 100 bins, this would
be `np.linspace(-1000, 1000, 100)`)
:param row_order: Array-like object containing row order -- typically
the result of an `np.argsort` call.
:param strip: Include axes along the left side with points that can be
clicked to spawn a minibrowser for that feature.
"""
nrows = self.diffed_array.shape[0]
if row_order is None:
row_order = np.arange(nrows)
extent = (min(x), max(x), 0, nrows)
axes_info = metaseq.plotutils.matrix_and_line_shell(strip=strip)
fig, matrix_ax, line_ax, strip_ax, cbar_ax = axes_info
_imshow_kwargs = dict(
aspect='auto', extent=extent, interpolation='nearest')
if imshow_kwargs:
_imshow_kwargs.update(imshow_kwargs)
if 'cmap' not in _imshow_kwargs:
_imshow_kwargs['cmap'] = metaseq.colormap_adjust.smart_colormap(
self.diffed_array.min(),
self.diffed_array.max()
)
mappable = matrix_ax.imshow(
self.diffed_array[row_order],
**_imshow_kwargs)
plt.colorbar(mappable, cbar_ax)
line_ax.plot(x, self.diffed_array.mean(axis=0))
if strip_ax:
line, = strip_ax.plot(np.zeros((nrows,)), np.arange(nrows) + 0.5,
**self._strip_kwargs)
line.features = self.features
line.ind = row_order
matrix_ax.axis('tight')
if strip_ax:
strip_ax.xaxis.set_visible(False)
matrix_ax.yaxis.set_visible(False)
matrix_ax.xaxis.set_visible(False)
if self.db:
self.minibrowser = GeneChipseqMiniBrowser(
[self.ip, self.control],
db=self.db,
plotting_kwargs=self.browser_plotting_kwargs,
local_coverage_kwargs=self.browser_local_coverage_kwargs)
else:
self.minibrowser = SignalChipseqMiniBrowser(
[self.ip, self.control],
plotting_kwargs=self.browser_plotting_kwargs,
local_coverage_kwargs=self.browser_local_coverage_kwargs)
fig.canvas.mpl_connect('pick_event', self.callback)
self.fig = fig
self.axes = {
'matrix_ax': matrix_ax,
'strip_ax': strip_ax,
'line_ax': line_ax,
'cbar_ax': cbar_ax
} |
0, module; 1, function_definition; 2, function_name:_restricted_growth_notation; 3, parameters; 4, block; 5, identifier:l; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, expression_statement; 11, for_statement; 12, return_statement; 13, comment:""" The clustering returned by the hcluster module gives group
membership without regard for numerical order This function preserves
the group membership, but sorts the labelling into numerical order """; 14, assignment; 15, assignment; 16, tuple_pattern; 17, call; 18, block; 19, assignment; 20, tuple_pattern; 21, call; 22, block; 23, call; 24, identifier:list_length; 25, call; 26, identifier:d; 27, call; 28, identifier:i; 29, identifier:element; 30, identifier:enumerate; 31, argument_list; 32, expression_statement; 33, identifier:l2; 34, binary_operator:[None] * list_length; 35, identifier:name; 36, identifier:index_list; 37, identifier:enumerate; 38, argument_list; 39, for_statement; 40, identifier:tuple; 41, argument_list; 42, identifier:len; 43, argument_list; 44, identifier:defaultdict; 45, argument_list; 46, identifier:l; 47, call; 48, list; 49, identifier:list_length; 50, call; 51, identifier:index; 52, identifier:index_list; 53, block; 54, identifier:l2; 55, identifier:l; 56, identifier:list; 57, attribute; 58, argument_list; 59, None; 60, identifier:sorted; 61, argument_list; 62, expression_statement; 63, subscript; 64, identifier:append; 65, identifier:i; 66, call; 67, keyword_argument; 68, assignment; 69, identifier:d; 70, identifier:element; 71, attribute; 72, argument_list; 73, identifier:key; 74, identifier:min; 75, subscript; 76, identifier:name; 77, identifier:d; 78, identifier:values; 79, identifier:l2; 80, identifier:index | 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; 9, 17; 9, 18; 10, 19; 11, 20; 11, 21; 11, 22; 12, 23; 14, 24; 14, 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; 25, 42; 25, 43; 27, 44; 27, 45; 31, 46; 32, 47; 34, 48; 34, 49; 38, 50; 39, 51; 39, 52; 39, 53; 41, 54; 43, 55; 45, 56; 47, 57; 47, 58; 48, 59; 50, 60; 50, 61; 53, 62; 57, 63; 57, 64; 58, 65; 61, 66; 61, 67; 62, 68; 63, 69; 63, 70; 66, 71; 66, 72; 67, 73; 67, 74; 68, 75; 68, 76; 71, 77; 71, 78; 75, 79; 75, 80 | def _restricted_growth_notation(l):
""" The clustering returned by the hcluster module gives group
membership without regard for numerical order This function preserves
the group membership, but sorts the labelling into numerical order """
list_length = len(l)
d = defaultdict(list)
for (i, element) in enumerate(l):
d[element].append(i)
l2 = [None] * list_length
for (name, index_list) in enumerate(sorted(d.values(), key=min)):
for index in index_list:
l2[index] = name
return tuple(l2) |
0, module; 1, function_definition; 2, function_name:insort_no_dup; 3, parameters; 4, block; 5, identifier:lst; 6, identifier:item; 7, expression_statement; 8, import_statement; 9, expression_statement; 10, if_statement; 11, comment:"""
If item is not in lst, add item to list at its sorted position
"""; 12, dotted_name; 13, assignment; 14, comparison_operator:lst[ix] != item; 15, block; 16, identifier:bisect; 17, identifier:ix; 18, call; 19, subscript; 20, identifier:item; 21, expression_statement; 22, attribute; 23, argument_list; 24, identifier:lst; 25, identifier:ix; 26, assignment; 27, identifier:bisect; 28, identifier:bisect_left; 29, identifier:lst; 30, identifier:item; 31, subscript; 32, list; 33, identifier:lst; 34, slice; 35, identifier:item; 36, identifier:ix; 37, identifier:ix | 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; 10, 14; 10, 15; 12, 16; 13, 17; 13, 18; 14, 19; 14, 20; 15, 21; 18, 22; 18, 23; 19, 24; 19, 25; 21, 26; 22, 27; 22, 28; 23, 29; 23, 30; 26, 31; 26, 32; 31, 33; 31, 34; 32, 35; 34, 36; 34, 37 | def insort_no_dup(lst, item):
"""
If item is not in lst, add item to list at its sorted position
"""
import bisect
ix = bisect.bisect_left(lst, item)
if lst[ix] != item:
lst[ix:ix] = [item] |
0, module; 1, function_definition; 2, function_name:records; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, return_statement; 8, comment:""" Returns a list of records in SORT_KEY order """; 9, list_comprehension; 10, subscript; 11, for_in_clause; 12, attribute; 13, identifier:i; 14, identifier:i; 15, call; 16, identifier:self; 17, identifier:_records; 18, identifier:range; 19, argument_list; 20, call; 21, identifier:len; 22, argument_list; 23, attribute; 24, identifier:self; 25, identifier:_records | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 9, 10; 9, 11; 10, 12; 10, 13; 11, 14; 11, 15; 12, 16; 12, 17; 15, 18; 15, 19; 19, 20; 20, 21; 20, 22; 22, 23; 23, 24; 23, 25 | def records(self):
""" Returns a list of records in SORT_KEY order """
return [self._records[i] for i in range(len(self._records))] |
0, module; 1, function_definition; 2, function_name:score; 3, parameters; 4, block; 5, identifier:self; 6, identifier:phone_number; 7, identifier:account_lifecycle_event; 8, dictionary_splat_pattern; 9, expression_statement; 10, return_statement; 11, identifier:params; 12, comment:"""
Score is an API that delivers reputation scoring based on phone number intelligence, traffic patterns, machine
learning, and a global data consortium.
See https://developer.telesign.com/docs/score-api for detailed API documentation.
"""; 13, call; 14, attribute; 15, argument_list; 16, identifier:self; 17, identifier:post; 18, call; 19, keyword_argument; 20, dictionary_splat; 21, attribute; 22, argument_list; 23, identifier:account_lifecycle_event; 24, identifier:account_lifecycle_event; 25, identifier:params; 26, identifier:SCORE_RESOURCE; 27, identifier:format; 28, keyword_argument; 29, identifier:phone_number; 30, identifier:phone_number | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 8, 11; 9, 12; 10, 13; 13, 14; 13, 15; 14, 16; 14, 17; 15, 18; 15, 19; 15, 20; 18, 21; 18, 22; 19, 23; 19, 24; 20, 25; 21, 26; 21, 27; 22, 28; 28, 29; 28, 30 | def score(self, phone_number, account_lifecycle_event, **params):
"""
Score is an API that delivers reputation scoring based on phone number intelligence, traffic patterns, machine
learning, and a global data consortium.
See https://developer.telesign.com/docs/score-api for detailed API documentation.
"""
return self.post(SCORE_RESOURCE.format(phone_number=phone_number),
account_lifecycle_event=account_lifecycle_event,
**params) |
0, module; 1, function_definition; 2, function_name:sorted_members; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, if_statement; 11, expression_statement; 12, comment:"""
Iterate over sorted members of shape in the same order in which
the members are declared except yielding the required members before
any optional members.
"""; 13, assignment; 14, assignment; 15, pattern_list; 16, call; 17, block; 18, attribute; 19, comment:# ResponseMetadata is the first member for all output shapes.; 20, block; 21, yield; 22, identifier:members; 23, call; 24, identifier:required_names; 25, call; 26, identifier:name; 27, identifier:shape; 28, attribute; 29, argument_list; 30, expression_statement; 31, identifier:self; 32, identifier:is_output_shape; 33, expression_statement; 34, call; 35, attribute; 36, argument_list; 37, attribute; 38, argument_list; 39, attribute; 40, identifier:items; 41, assignment; 42, yield; 43, identifier:sorted; 44, argument_list; 45, identifier:collections; 46, identifier:OrderedDict; 47, attribute; 48, identifier:get; 49, string:"required"; 50, tuple; 51, identifier:self; 52, identifier:members; 53, subscript; 54, call; 55, call; 56, call; 57, keyword_argument; 58, identifier:self; 59, identifier:metadata; 60, identifier:members; 61, identifier:name; 62, identifier:AbShapeMember; 63, argument_list; 64, identifier:AbShapeMember; 65, argument_list; 66, attribute; 67, argument_list; 68, identifier:key; 69, lambda; 70, keyword_argument; 71, keyword_argument; 72, keyword_argument; 73, keyword_argument; 74, keyword_argument; 75, keyword_argument; 76, identifier:members; 77, identifier:values; 78, lambda_parameters; 79, not_operator; 80, identifier:name; 81, identifier:name; 82, identifier:shape; 83, identifier:shape; 84, identifier:is_required; 85, comparison_operator:name in required_names; 86, identifier:name; 87, string:"ResponseMetadata"; 88, identifier:shape; 89, call; 90, identifier:is_required; 91, True; 92, identifier:m; 93, attribute; 94, identifier:name; 95, identifier:required_names; 96, attribute; 97, argument_list; 98, identifier:m; 99, identifier:is_required; 100, attribute; 101, identifier:get_shape_by_name; 102, string:"ResponseMetadata"; 103, identifier:self; 104, identifier:_shape_resolver | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 7, 13; 8, 14; 9, 15; 9, 16; 9, 17; 10, 18; 10, 19; 10, 20; 11, 21; 13, 22; 13, 23; 14, 24; 14, 25; 15, 26; 15, 27; 16, 28; 16, 29; 17, 30; 18, 31; 18, 32; 20, 33; 21, 34; 23, 35; 23, 36; 25, 37; 25, 38; 28, 39; 28, 40; 30, 41; 33, 42; 34, 43; 34, 44; 35, 45; 35, 46; 37, 47; 37, 48; 38, 49; 38, 50; 39, 51; 39, 52; 41, 53; 41, 54; 42, 55; 44, 56; 44, 57; 47, 58; 47, 59; 53, 60; 53, 61; 54, 62; 54, 63; 55, 64; 55, 65; 56, 66; 56, 67; 57, 68; 57, 69; 63, 70; 63, 71; 63, 72; 65, 73; 65, 74; 65, 75; 66, 76; 66, 77; 69, 78; 69, 79; 70, 80; 70, 81; 71, 82; 71, 83; 72, 84; 72, 85; 73, 86; 73, 87; 74, 88; 74, 89; 75, 90; 75, 91; 78, 92; 79, 93; 85, 94; 85, 95; 89, 96; 89, 97; 93, 98; 93, 99; 96, 100; 96, 101; 97, 102; 100, 103; 100, 104 | def sorted_members(self):
"""
Iterate over sorted members of shape in the same order in which
the members are declared except yielding the required members before
any optional members.
"""
members = collections.OrderedDict()
required_names = self.metadata.get("required", ())
for name, shape in self.members.items():
members[name] = AbShapeMember(name=name, shape=shape, is_required=name in required_names)
if self.is_output_shape:
# ResponseMetadata is the first member for all output shapes.
yield AbShapeMember(
name="ResponseMetadata",
shape=self._shape_resolver.get_shape_by_name("ResponseMetadata"),
is_required=True,
)
yield from sorted(members.values(), key=lambda m: not m.is_required) |
0, module; 1, function_definition; 2, function_name:threshold_brier_score; 3, parameters; 4, block; 5, identifier:observations; 6, identifier:forecasts; 7, identifier:threshold; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, if_statement; 15, if_statement; 16, if_statement; 17, expression_statement; 18, if_statement; 19, if_statement; 20, expression_statement; 21, if_statement; 22, expression_statement; 23, if_statement; 24, return_statement; 25, identifier:issorted; 26, False; 27, identifier:axis; 28, unary_operator; 29, comment:"""
Calculate the Brier scores of an ensemble for exceeding given thresholds.
According to the threshold decomposition of CRPS, the resulting Brier
scores can thus be summed along the last axis to calculate CRPS, as
.. math::
CRPS(F, x) = \int_z BS(F(z), H(z - x)) dz
where $F(x) = \int_{z \leq x} p(z) dz$ is the cumulative distribution
function (CDF) of the forecast distribution $F$, $x$ is a point estimate of
the true observation (observational error is neglected), $BS$ denotes the
Brier score and $H(x)$ denotes the Heaviside step function, which we define
here as equal to 1 for x >= 0 and 0 otherwise.
It is more efficient to calculate CRPS directly, but this threshold
decomposition itself provides a useful summary of model quality as a
function of measurement values.
The Numba accelerated version of this function is much faster for
calculating many thresholds simultaneously: it runs in time
O(N * (E * log(E) + T)), where N is the number of observations, E is the
ensemble size and T is the number of thresholds.
The non-Numba accelerated version requires time and space O(N * E * T).
Parameters
----------
observations : float or array_like
Observations float or array. Missing values (NaN) are given scores of
NaN.
forecasts : float or array_like
Array of forecasts ensemble members, of the same shape as observations
except for the extra axis corresponding to the ensemble. If forecasts
has the same shape as observations, the forecasts are treated as
deterministic. Missing values (NaN) are ignored.
threshold : scalar or 1d array_like
Threshold value(s) at which to calculate exceedence Brier scores.
issorted : bool, optional
Optimization flag to indicate that the elements of `ensemble` are
already sorted along `axis`.
axis : int, optional
Axis in forecasts which corresponds to different ensemble members,
along which to calculate the threshold decomposition.
Returns
-------
out : np.ndarray
Brier scores at each thresold for each ensemble forecast against the
observations. If ``threshold`` is a scalar, the result will have the
same shape as observations. Otherwise, it will have an additional final
dimension corresponding to the threshold levels.
References
----------
Gneiting, T. and Ranjan, R. Comparing density forecasts using threshold-
and quantile-weighted scoring rules. J. Bus. Econ. Stat. 29, 411-422
(2011). http://www.stat.washington.edu/research/reports/2008/tr533.pdf
See also
--------
crps_ensemble, brier_score
"""; 30, assignment; 31, assignment; 32, assignment; 33, comparison_operator:axis != -1; 34, block; 35, comparison_operator:forecasts.shape == observations.shape; 36, block; 37, comparison_operator:observations.shape != forecasts.shape[:-1]; 38, block; 39, assignment; 40, comparison_operator:threshold.ndim > 1; 41, block; 42, boolean_operator; 43, block; 44, assignment; 45, not_operator; 46, block; 47, assignment; 48, identifier:scalar_threshold; 49, block; 50, identifier:result; 51, integer:1; 52, identifier:observations; 53, call; 54, identifier:threshold; 55, call; 56, identifier:forecasts; 57, call; 58, identifier:axis; 59, unary_operator; 60, expression_statement; 61, attribute; 62, attribute; 63, expression_statement; 64, attribute; 65, subscript; 66, raise_statement; 67, identifier:scalar_threshold; 68, comparison_operator:threshold.ndim == 0; 69, attribute; 70, integer:1; 71, raise_statement; 72, comparison_operator:threshold.ndim == 1; 73, not_operator; 74, raise_statement; 75, identifier:threshold; 76, call; 77, identifier:issorted; 78, expression_statement; 79, identifier:result; 80, call; 81, expression_statement; 82, attribute; 83, argument_list; 84, attribute; 85, argument_list; 86, attribute; 87, argument_list; 88, integer:1; 89, assignment; 90, identifier:forecasts; 91, identifier:shape; 92, identifier:observations; 93, identifier:shape; 94, assignment; 95, identifier:observations; 96, identifier:shape; 97, attribute; 98, slice; 99, call; 100, attribute; 101, integer:0; 102, identifier:threshold; 103, identifier:ndim; 104, call; 105, attribute; 106, integer:1; 107, call; 108, call; 109, attribute; 110, argument_list; 111, assignment; 112, identifier:_threshold_brier_score_core; 113, argument_list; 114, assignment; 115, identifier:np; 116, identifier:asarray; 117, identifier:observations; 118, identifier:np; 119, identifier:asarray; 120, identifier:threshold; 121, identifier:np; 122, identifier:asarray; 123, identifier:forecasts; 124, identifier:forecasts; 125, call; 126, identifier:forecasts; 127, subscript; 128, identifier:forecasts; 129, identifier:shape; 130, unary_operator; 131, identifier:ValueError; 132, argument_list; 133, identifier:threshold; 134, identifier:ndim; 135, identifier:ValueError; 136, argument_list; 137, identifier:threshold; 138, identifier:ndim; 139, attribute; 140, argument_list; 141, identifier:ValueError; 142, argument_list; 143, identifier:threshold; 144, identifier:reshape; 145, binary_operator:(1,) * observations.ndim + (-1,); 146, identifier:forecasts; 147, call; 148, identifier:observations; 149, identifier:forecasts; 150, identifier:threshold; 151, identifier:result; 152, call; 153, identifier:move_axis_to_end; 154, argument_list; 155, identifier:forecasts; 156, ellipsis:...; 157, attribute; 158, integer:1; 159, binary_operator:'observations and forecasts must have matching '
'shapes or matching shapes except along `axis=%s`'
% axis; 160, string; 161, parenthesized_expression; 162, identifier:all; 163, string; 164, binary_operator:(1,) * observations.ndim; 165, tuple; 166, attribute; 167, argument_list; 168, attribute; 169, argument_list; 170, identifier:forecasts; 171, identifier:axis; 172, identifier:np; 173, identifier:newaxis; 174, concatenated_string; 175, identifier:axis; 176, string_content:threshold must be scalar or 1-dimensional; 177, comparison_operator:np.sort(threshold) == threshold; 178, string_content:1D thresholds must be sorted; 179, tuple; 180, attribute; 181, unary_operator; 182, identifier:np; 183, identifier:sort; 184, identifier:forecasts; 185, keyword_argument; 186, identifier:result; 187, identifier:squeeze; 188, keyword_argument; 189, string; 190, string; 191, call; 192, identifier:threshold; 193, integer:1; 194, identifier:observations; 195, identifier:ndim; 196, integer:1; 197, identifier:axis; 198, unary_operator; 199, identifier:axis; 200, unary_operator; 201, string_content:observations and forecasts must have matching; 202, string_content:shapes or matching shapes except along `axis=%s`; 203, attribute; 204, argument_list; 205, integer:1; 206, integer:1; 207, identifier:np; 208, identifier:sort; 209, identifier:threshold | 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; 4, 23; 4, 24; 8, 25; 8, 26; 9, 27; 9, 28; 10, 29; 11, 30; 12, 31; 13, 32; 14, 33; 14, 34; 15, 35; 15, 36; 16, 37; 16, 38; 17, 39; 18, 40; 18, 41; 19, 42; 19, 43; 20, 44; 21, 45; 21, 46; 22, 47; 23, 48; 23, 49; 24, 50; 28, 51; 30, 52; 30, 53; 31, 54; 31, 55; 32, 56; 32, 57; 33, 58; 33, 59; 34, 60; 35, 61; 35, 62; 36, 63; 37, 64; 37, 65; 38, 66; 39, 67; 39, 68; 40, 69; 40, 70; 41, 71; 42, 72; 42, 73; 43, 74; 44, 75; 44, 76; 45, 77; 46, 78; 47, 79; 47, 80; 49, 81; 53, 82; 53, 83; 55, 84; 55, 85; 57, 86; 57, 87; 59, 88; 60, 89; 61, 90; 61, 91; 62, 92; 62, 93; 63, 94; 64, 95; 64, 96; 65, 97; 65, 98; 66, 99; 68, 100; 68, 101; 69, 102; 69, 103; 71, 104; 72, 105; 72, 106; 73, 107; 74, 108; 76, 109; 76, 110; 78, 111; 80, 112; 80, 113; 81, 114; 82, 115; 82, 116; 83, 117; 84, 118; 84, 119; 85, 120; 86, 121; 86, 122; 87, 123; 89, 124; 89, 125; 94, 126; 94, 127; 97, 128; 97, 129; 98, 130; 99, 131; 99, 132; 100, 133; 100, 134; 104, 135; 104, 136; 105, 137; 105, 138; 107, 139; 107, 140; 108, 141; 108, 142; 109, 143; 109, 144; 110, 145; 111, 146; 111, 147; 113, 148; 113, 149; 113, 150; 114, 151; 114, 152; 125, 153; 125, 154; 127, 155; 127, 156; 127, 157; 130, 158; 132, 159; 136, 160; 139, 161; 139, 162; 142, 163; 145, 164; 145, 165; 147, 166; 147, 167; 152, 168; 152, 169; 154, 170; 154, 171; 157, 172; 157, 173; 159, 174; 159, 175; 160, 176; 161, 177; 163, 178; 164, 179; 164, 180; 165, 181; 166, 182; 166, 183; 167, 184; 167, 185; 168, 186; 168, 187; 169, 188; 174, 189; 174, 190; 177, 191; 177, 192; 179, 193; 180, 194; 180, 195; 181, 196; 185, 197; 185, 198; 188, 199; 188, 200; 189, 201; 190, 202; 191, 203; 191, 204; 198, 205; 200, 206; 203, 207; 203, 208; 204, 209 | def threshold_brier_score(observations, forecasts, threshold, issorted=False,
axis=-1):
"""
Calculate the Brier scores of an ensemble for exceeding given thresholds.
According to the threshold decomposition of CRPS, the resulting Brier
scores can thus be summed along the last axis to calculate CRPS, as
.. math::
CRPS(F, x) = \int_z BS(F(z), H(z - x)) dz
where $F(x) = \int_{z \leq x} p(z) dz$ is the cumulative distribution
function (CDF) of the forecast distribution $F$, $x$ is a point estimate of
the true observation (observational error is neglected), $BS$ denotes the
Brier score and $H(x)$ denotes the Heaviside step function, which we define
here as equal to 1 for x >= 0 and 0 otherwise.
It is more efficient to calculate CRPS directly, but this threshold
decomposition itself provides a useful summary of model quality as a
function of measurement values.
The Numba accelerated version of this function is much faster for
calculating many thresholds simultaneously: it runs in time
O(N * (E * log(E) + T)), where N is the number of observations, E is the
ensemble size and T is the number of thresholds.
The non-Numba accelerated version requires time and space O(N * E * T).
Parameters
----------
observations : float or array_like
Observations float or array. Missing values (NaN) are given scores of
NaN.
forecasts : float or array_like
Array of forecasts ensemble members, of the same shape as observations
except for the extra axis corresponding to the ensemble. If forecasts
has the same shape as observations, the forecasts are treated as
deterministic. Missing values (NaN) are ignored.
threshold : scalar or 1d array_like
Threshold value(s) at which to calculate exceedence Brier scores.
issorted : bool, optional
Optimization flag to indicate that the elements of `ensemble` are
already sorted along `axis`.
axis : int, optional
Axis in forecasts which corresponds to different ensemble members,
along which to calculate the threshold decomposition.
Returns
-------
out : np.ndarray
Brier scores at each thresold for each ensemble forecast against the
observations. If ``threshold`` is a scalar, the result will have the
same shape as observations. Otherwise, it will have an additional final
dimension corresponding to the threshold levels.
References
----------
Gneiting, T. and Ranjan, R. Comparing density forecasts using threshold-
and quantile-weighted scoring rules. J. Bus. Econ. Stat. 29, 411-422
(2011). http://www.stat.washington.edu/research/reports/2008/tr533.pdf
See also
--------
crps_ensemble, brier_score
"""
observations = np.asarray(observations)
threshold = np.asarray(threshold)
forecasts = np.asarray(forecasts)
if axis != -1:
forecasts = move_axis_to_end(forecasts, axis)
if forecasts.shape == observations.shape:
forecasts = forecasts[..., np.newaxis]
if observations.shape != forecasts.shape[:-1]:
raise ValueError('observations and forecasts must have matching '
'shapes or matching shapes except along `axis=%s`'
% axis)
scalar_threshold = threshold.ndim == 0
if threshold.ndim > 1:
raise ValueError('threshold must be scalar or 1-dimensional')
if threshold.ndim == 1 and not (np.sort(threshold) == threshold).all():
raise ValueError('1D thresholds must be sorted')
threshold = threshold.reshape((1,) * observations.ndim + (-1,))
if not issorted:
forecasts = np.sort(forecasts, axis=-1)
result = _threshold_brier_score_core(observations, forecasts, threshold)
if scalar_threshold:
result = result.squeeze(axis=-1)
return result |
0, module; 1, function_definition; 2, function_name:run; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, if_statement; 11, identifier:N; 12, integer:1; 13, identifier:trace_sort; 14, False; 15, string; 16, comparison_operator:N == 0; 17, block; 18, identifier:trace_sort; 19, block; 20, else_clause; 21, string_content:Run the sampler, store the history of visited points into
the member variable ``self.samples`` and the importance weights
into ``self.weights``.
.. seealso::
:py:class:`pypmc.tools.History`
:param N:
Integer; the number of samples to be drawn.
:param trace_sort:
Bool; if True, return an array containing the responsible
component of ``self.proposal`` for each sample generated
during this run.
.. note::
This option only works for proposals of type
:py:class:`pypmc.density.mixture.MixtureDensity`
.. note::
If True, the samples will be ordered by the components.; 22, identifier:N; 23, integer:0; 24, return_statement; 25, expression_statement; 26, expression_statement; 27, return_statement; 28, block; 29, integer:0; 30, assignment; 31, call; 32, identifier:origin; 33, expression_statement; 34, expression_statement; 35, pattern_list; 36, call; 37, attribute; 38, argument_list; 39, assignment; 40, call; 41, identifier:this_samples; 42, identifier:origin; 43, attribute; 44, argument_list; 45, identifier:self; 46, identifier:_calculate_weights; 47, identifier:this_samples; 48, identifier:N; 49, identifier:this_samples; 50, call; 51, attribute; 52, argument_list; 53, identifier:self; 54, identifier:_get_samples; 55, identifier:N; 56, keyword_argument; 57, attribute; 58, argument_list; 59, identifier:self; 60, identifier:_calculate_weights; 61, identifier:this_samples; 62, identifier:N; 63, identifier:trace_sort; 64, True; 65, identifier:self; 66, identifier:_get_samples; 67, identifier:N; 68, keyword_argument; 69, identifier:trace_sort; 70, False | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 6, 11; 6, 12; 7, 13; 7, 14; 8, 15; 9, 16; 9, 17; 10, 18; 10, 19; 10, 20; 15, 21; 16, 22; 16, 23; 17, 24; 19, 25; 19, 26; 19, 27; 20, 28; 24, 29; 25, 30; 26, 31; 27, 32; 28, 33; 28, 34; 30, 35; 30, 36; 31, 37; 31, 38; 33, 39; 34, 40; 35, 41; 35, 42; 36, 43; 36, 44; 37, 45; 37, 46; 38, 47; 38, 48; 39, 49; 39, 50; 40, 51; 40, 52; 43, 53; 43, 54; 44, 55; 44, 56; 50, 57; 50, 58; 51, 59; 51, 60; 52, 61; 52, 62; 56, 63; 56, 64; 57, 65; 57, 66; 58, 67; 58, 68; 68, 69; 68, 70 | def run(self, N=1, trace_sort=False):
'''Run the sampler, store the history of visited points into
the member variable ``self.samples`` and the importance weights
into ``self.weights``.
.. seealso::
:py:class:`pypmc.tools.History`
:param N:
Integer; the number of samples to be drawn.
:param trace_sort:
Bool; if True, return an array containing the responsible
component of ``self.proposal`` for each sample generated
during this run.
.. note::
This option only works for proposals of type
:py:class:`pypmc.density.mixture.MixtureDensity`
.. note::
If True, the samples will be ordered by the components.
'''
if N == 0:
return 0
if trace_sort:
this_samples, origin = self._get_samples(N, trace_sort=True)
self._calculate_weights(this_samples, N)
return origin
else:
this_samples = self._get_samples(N, trace_sort=False)
self._calculate_weights(this_samples, N) |
0, module; 1, function_definition; 2, function_name:_get_samples; 3, parameters; 4, block; 5, identifier:self; 6, identifier:N; 7, identifier:trace_sort; 8, expression_statement; 9, comment:# allocate an empty numpy array to store the run and append accept count; 10, comment:# (importance sampling accepts all points); 11, expression_statement; 12, comment:# store the proposed points (weights are still to be calculated); 13, if_statement; 14, comment:"""Save N samples from ``self.proposal`` to ``self.samples``
This function does NOT calculate the weights.
Return a reference to this run's samples in ``self.samples``.
If ``trace_sort`` is True, additionally return an array
indicating the responsible component. (MixtureDensity only)
"""; 15, assignment; 16, identifier:trace_sort; 17, block; 18, else_clause; 19, identifier:this_run; 20, call; 21, expression_statement; 22, return_statement; 23, block; 24, attribute; 25, argument_list; 26, assignment; 27, expression_list; 28, expression_statement; 29, return_statement; 30, attribute; 31, identifier:append; 32, identifier:N; 33, pattern_list; 34, call; 35, identifier:this_run; 36, identifier:origin; 37, assignment; 38, identifier:this_run; 39, identifier:self; 40, identifier:samples; 41, subscript; 42, identifier:origin; 43, attribute; 44, argument_list; 45, subscript; 46, call; 47, identifier:this_run; 48, slice; 49, attribute; 50, identifier:propose; 51, identifier:N; 52, attribute; 53, keyword_argument; 54, keyword_argument; 55, identifier:this_run; 56, slice; 57, attribute; 58, argument_list; 59, identifier:self; 60, identifier:proposal; 61, identifier:self; 62, identifier:rng; 63, identifier:trace; 64, True; 65, identifier:shuffle; 66, False; 67, attribute; 68, identifier:propose; 69, identifier:N; 70, attribute; 71, identifier:self; 72, identifier:proposal; 73, identifier:self; 74, identifier:rng | 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; 11, 15; 13, 16; 13, 17; 13, 18; 15, 19; 15, 20; 17, 21; 17, 22; 18, 23; 20, 24; 20, 25; 21, 26; 22, 27; 23, 28; 23, 29; 24, 30; 24, 31; 25, 32; 26, 33; 26, 34; 27, 35; 27, 36; 28, 37; 29, 38; 30, 39; 30, 40; 33, 41; 33, 42; 34, 43; 34, 44; 37, 45; 37, 46; 41, 47; 41, 48; 43, 49; 43, 50; 44, 51; 44, 52; 44, 53; 44, 54; 45, 55; 45, 56; 46, 57; 46, 58; 49, 59; 49, 60; 52, 61; 52, 62; 53, 63; 53, 64; 54, 65; 54, 66; 57, 67; 57, 68; 58, 69; 58, 70; 67, 71; 67, 72; 70, 73; 70, 74 | def _get_samples(self, N, trace_sort):
"""Save N samples from ``self.proposal`` to ``self.samples``
This function does NOT calculate the weights.
Return a reference to this run's samples in ``self.samples``.
If ``trace_sort`` is True, additionally return an array
indicating the responsible component. (MixtureDensity only)
"""
# allocate an empty numpy array to store the run and append accept count
# (importance sampling accepts all points)
this_run = self.samples.append(N)
# store the proposed points (weights are still to be calculated)
if trace_sort:
this_run[:], origin = self.proposal.propose(N, self.rng, trace=True, shuffle=False)
return this_run, origin
else:
this_run[:] = self.proposal.propose(N, self.rng)
return this_run |
0, module; 1, function_definition; 2, function_name:argsort_indices; 3, parameters; 4, block; 5, identifier:a; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, identifier:axis; 13, unary_operator; 14, comment:"""Like argsort, but returns an index suitable for sorting the
the original array even if that array is multidimensional
"""; 15, assignment; 16, assignment; 17, assignment; 18, call; 19, integer:1; 20, identifier:a; 21, call; 22, identifier:ind; 23, call; 24, subscript; 25, call; 26, identifier:tuple; 27, argument_list; 28, attribute; 29, argument_list; 30, identifier:list; 31, argument_list; 32, identifier:ind; 33, identifier:axis; 34, attribute; 35, argument_list; 36, identifier:ind; 37, identifier:np; 38, identifier:asarray; 39, identifier:a; 40, call; 41, identifier:a; 42, identifier:argsort; 43, identifier:axis; 44, attribute; 45, argument_list; 46, identifier:np; 47, identifier:ix_; 48, list_splat; 49, list_comprehension; 50, call; 51, for_in_clause; 52, attribute; 53, argument_list; 54, identifier:d; 55, attribute; 56, identifier:np; 57, identifier:arange; 58, identifier:d; 59, identifier:a; 60, identifier:shape | 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; 10, 17; 11, 18; 13, 19; 15, 20; 15, 21; 16, 22; 16, 23; 17, 24; 17, 25; 18, 26; 18, 27; 21, 28; 21, 29; 23, 30; 23, 31; 24, 32; 24, 33; 25, 34; 25, 35; 27, 36; 28, 37; 28, 38; 29, 39; 31, 40; 34, 41; 34, 42; 35, 43; 40, 44; 40, 45; 44, 46; 44, 47; 45, 48; 48, 49; 49, 50; 49, 51; 50, 52; 50, 53; 51, 54; 51, 55; 52, 56; 52, 57; 53, 58; 55, 59; 55, 60 | def argsort_indices(a, axis=-1):
"""Like argsort, but returns an index suitable for sorting the
the original array even if that array is multidimensional
"""
a = np.asarray(a)
ind = list(np.ix_(*[np.arange(d) for d in a.shape]))
ind[axis] = a.argsort(axis)
return tuple(ind) |
0, module; 1, function_definition; 2, function_name:sorted; 3, parameters; 4, block; 5, identifier:collection; 6, expression_statement; 7, if_statement; 8, if_statement; 9, if_statement; 10, return_statement; 11, comment:"""
sorting dict by key,
schema-collection by schema-name
operations by id
"""; 12, comparison_operator:len(collection) < 1; 13, block; 14, call; 15, block; 16, call; 17, block; 18, elif_clause; 19, else_clause; 20, call; 21, call; 22, integer:1; 23, return_statement; 24, identifier:isinstance; 25, argument_list; 26, return_statement; 27, identifier:isinstance; 28, argument_list; 29, expression_statement; 30, call; 31, block; 32, block; 33, identifier:sorted; 34, argument_list; 35, identifier:len; 36, argument_list; 37, identifier:collection; 38, identifier:collection; 39, identifier:dict; 40, call; 41, subscript; 42, identifier:Operation; 43, assignment; 44, identifier:isinstance; 45, argument_list; 46, expression_statement; 47, raise_statement; 48, identifier:collection; 49, keyword_argument; 50, identifier:collection; 51, identifier:sorted; 52, argument_list; 53, call; 54, integer:0; 55, identifier:key; 56, lambda; 57, subscript; 58, identifier:str; 59, assignment; 60, call; 61, identifier:key; 62, identifier:key; 63, call; 64, keyword_argument; 65, identifier:list; 66, argument_list; 67, lambda_parameters; 68, attribute; 69, call; 70, integer:0; 71, identifier:key; 72, lambda; 73, identifier:TypeError; 74, argument_list; 75, attribute; 76, argument_list; 77, identifier:key; 78, lambda; 79, identifier:collection; 80, identifier:x; 81, identifier:x; 82, identifier:operation_id; 83, identifier:list; 84, argument_list; 85, lambda_parameters; 86, attribute; 87, call; 88, identifier:collection; 89, identifier:items; 90, lambda_parameters; 91, subscript; 92, identifier:collection; 93, identifier:x; 94, call; 95, identifier:name; 96, identifier:type; 97, argument_list; 98, identifier:x; 99, identifier:x; 100, integer:0; 101, attribute; 102, argument_list; 103, subscript; 104, identifier:SchemaObjects; 105, identifier:get; 106, identifier:x; 107, identifier:collection; 108, integer:0 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 7, 13; 8, 14; 8, 15; 9, 16; 9, 17; 9, 18; 9, 19; 10, 20; 12, 21; 12, 22; 13, 23; 14, 24; 14, 25; 15, 26; 16, 27; 16, 28; 17, 29; 18, 30; 18, 31; 19, 32; 20, 33; 20, 34; 21, 35; 21, 36; 23, 37; 25, 38; 25, 39; 26, 40; 28, 41; 28, 42; 29, 43; 30, 44; 30, 45; 31, 46; 32, 47; 34, 48; 34, 49; 36, 50; 40, 51; 40, 52; 41, 53; 41, 54; 43, 55; 43, 56; 45, 57; 45, 58; 46, 59; 47, 60; 49, 61; 49, 62; 52, 63; 52, 64; 53, 65; 53, 66; 56, 67; 56, 68; 57, 69; 57, 70; 59, 71; 59, 72; 60, 73; 60, 74; 63, 75; 63, 76; 64, 77; 64, 78; 66, 79; 67, 80; 68, 81; 68, 82; 69, 83; 69, 84; 72, 85; 72, 86; 74, 87; 75, 88; 75, 89; 78, 90; 78, 91; 84, 92; 85, 93; 86, 94; 86, 95; 87, 96; 87, 97; 90, 98; 91, 99; 91, 100; 94, 101; 94, 102; 97, 103; 101, 104; 101, 105; 102, 106; 103, 107; 103, 108 | def sorted(collection):
"""
sorting dict by key,
schema-collection by schema-name
operations by id
"""
if len(collection) < 1:
return collection
if isinstance(collection, dict):
return sorted(collection.items(), key=lambda x: x[0])
if isinstance(list(collection)[0], Operation):
key = lambda x: x.operation_id
elif isinstance(list(collection)[0], str):
key = lambda x: SchemaObjects.get(x).name
else:
raise TypeError(type(collection[0]))
return sorted(collection, key=key) |
0, module; 1, function_definition; 2, function_name:get_schemas; 3, parameters; 4, block; 5, identifier:cls; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, if_statement; 12, return_statement; 13, identifier:schema_types; 14, None; 15, identifier:sort; 16, True; 17, comment:"""
Get schemas by type. If ``schema_type`` is None, return all schemas
:param schema_types: list of schema types
:type schema_types: list or None
:param bool sort: sort by name
:return: list of schemas
:rtype: list
"""; 18, assignment; 19, identifier:schema_types; 20, block; 21, identifier:sort; 22, block; 23, identifier:result; 24, identifier:result; 25, call; 26, expression_statement; 27, expression_statement; 28, identifier:filter; 29, argument_list; 30, assignment; 31, assignment; 32, lambda; 33, call; 34, identifier:result; 35, call; 36, identifier:result; 37, call; 38, lambda_parameters; 39, not_operator; 40, attribute; 41, argument_list; 42, identifier:filter; 43, argument_list; 44, identifier:sorted; 45, argument_list; 46, identifier:x; 47, attribute; 48, attribute; 49, identifier:values; 50, lambda; 51, identifier:result; 52, identifier:result; 53, keyword_argument; 54, identifier:x; 55, identifier:is_inline_array; 56, identifier:cls; 57, identifier:_schemas; 58, lambda_parameters; 59, comparison_operator:x.schema_type in schema_types; 60, identifier:key; 61, call; 62, identifier:x; 63, attribute; 64, identifier:schema_types; 65, identifier:attrgetter; 66, argument_list; 67, identifier:x; 68, identifier:schema_type; 69, string; 70, string_content:name | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 6, 13; 6, 14; 7, 15; 7, 16; 8, 17; 9, 18; 10, 19; 10, 20; 11, 21; 11, 22; 12, 23; 18, 24; 18, 25; 20, 26; 22, 27; 25, 28; 25, 29; 26, 30; 27, 31; 29, 32; 29, 33; 30, 34; 30, 35; 31, 36; 31, 37; 32, 38; 32, 39; 33, 40; 33, 41; 35, 42; 35, 43; 37, 44; 37, 45; 38, 46; 39, 47; 40, 48; 40, 49; 43, 50; 43, 51; 45, 52; 45, 53; 47, 54; 47, 55; 48, 56; 48, 57; 50, 58; 50, 59; 53, 60; 53, 61; 58, 62; 59, 63; 59, 64; 61, 65; 61, 66; 63, 67; 63, 68; 66, 69; 69, 70 | def get_schemas(cls, schema_types=None, sort=True):
"""
Get schemas by type. If ``schema_type`` is None, return all schemas
:param schema_types: list of schema types
:type schema_types: list or None
:param bool sort: sort by name
:return: list of schemas
:rtype: list
"""
result = filter(lambda x: not x.is_inline_array, cls._schemas.values())
if schema_types:
result = filter(lambda x: x.schema_type in schema_types, result)
if sort:
result = sorted(result, key=attrgetter('name'))
return result |
0, module; 1, function_definition; 2, function_name:to_molden; 3, parameters; 4, block; 5, identifier:cartesian_list; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, if_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, if_statement; 20, identifier:buf; 21, None; 22, identifier:sort_index; 23, True; 24, identifier:overwrite; 25, True; 26, identifier:float_format; 27, attribute; 28, comment:"""Write a list of Cartesians into a molden file.
.. note:: Since it permamently writes a file, this function
is strictly speaking **not sideeffect free**.
The list to be written is of course not changed.
Args:
cartesian_list (list):
buf (str): StringIO-like, optional buffer to write to
sort_index (bool): If sort_index is true, the Cartesian
is sorted by the index before writing.
overwrite (bool): May overwrite existing files.
float_format (one-parameter function): Formatter function
to apply to column’s elements if they are floats.
The result of this function must be a unicode string.
Returns:
formatted : string (or unicode, depending on data and options)
"""; 29, identifier:sort_index; 30, block; 31, assignment; 32, assignment; 33, assignment; 34, assignment; 35, assignment; 36, assignment; 37, assignment; 38, comparison_operator:buf is not None; 39, block; 40, else_clause; 41, string; 42, identifier:format; 43, expression_statement; 44, identifier:give_header; 45, attribute; 46, identifier:values; 47, binary_operator:len(cartesian_list) * '1\n'; 48, identifier:energy; 49, list_comprehension; 50, identifier:energy; 51, binary_operator:'\n'.join(energy) + '\n'; 52, identifier:header; 53, call; 54, identifier:coordinates; 55, list_comprehension; 56, identifier:output; 57, binary_operator:header + '\n'.join(coordinates); 58, identifier:buf; 59, None; 60, if_statement; 61, block; 62, string_content:{:.6f}; 63, assignment; 64, parenthesized_expression; 65, identifier:format; 66, call; 67, string; 68, call; 69, for_in_clause; 70, call; 71, string; 72, identifier:give_header; 73, argument_list; 74, call; 75, for_in_clause; 76, identifier:header; 77, call; 78, identifier:overwrite; 79, block; 80, else_clause; 81, return_statement; 82, identifier:cartesian_list; 83, list_comprehension; 84, binary_operator:"[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)) + "\n"
+ '[GEOCONV]\n'
+ 'energy\n{energy}'
+ 'max-force\n{max_force}'
+ 'rms-force\n{rms_force}'
+ '[GEOMETRIES] (XYZ)\n'; 85, identifier:len; 86, argument_list; 87, string_content; 88, identifier:str; 89, argument_list; 90, identifier:m; 91, identifier:cartesian_list; 92, attribute; 93, argument_list; 94, string_content; 95, keyword_argument; 96, keyword_argument; 97, keyword_argument; 98, attribute; 99, argument_list; 100, identifier:x; 101, identifier:cartesian_list; 102, attribute; 103, argument_list; 104, with_statement; 105, block; 106, identifier:output; 107, call; 108, for_in_clause; 109, binary_operator:"[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)) + "\n"
+ '[GEOCONV]\n'
+ 'energy\n{energy}'
+ 'max-force\n{max_force}'
+ 'rms-force\n{rms_force}'; 110, string; 111, identifier:cartesian_list; 112, escape_sequence:\n; 113, call; 114, string; 115, identifier:join; 116, identifier:energy; 117, escape_sequence:\n; 118, identifier:energy; 119, identifier:energy; 120, identifier:max_force; 121, identifier:values; 122, identifier:rms_force; 123, identifier:values; 124, identifier:x; 125, identifier:to_xyz; 126, keyword_argument; 127, keyword_argument; 128, string; 129, identifier:join; 130, identifier:coordinates; 131, with_clause; 132, block; 133, with_statement; 134, attribute; 135, argument_list; 136, identifier:molecule; 137, identifier:cartesian_list; 138, binary_operator:"[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)) + "\n"
+ '[GEOCONV]\n'
+ 'energy\n{energy}'
+ 'max-force\n{max_force}'; 139, string; 140, string_content; 141, attribute; 142, argument_list; 143, string_content; 144, identifier:sort_index; 145, identifier:sort_index; 146, identifier:float_format; 147, identifier:float_format; 148, string_content; 149, with_item; 150, expression_statement; 151, with_clause; 152, block; 153, identifier:molecule; 154, identifier:sort_index; 155, binary_operator:"[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)) + "\n"
+ '[GEOCONV]\n'
+ 'energy\n{energy}'; 156, string; 157, string_content; 158, escape_sequence:\n; 159, attribute; 160, identifier:get; 161, string; 162, integer:1; 163, escape_sequence:\n; 164, escape_sequence:\n; 165, as_pattern; 166, call; 167, with_item; 168, expression_statement; 169, binary_operator:"[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)) + "\n"
+ '[GEOCONV]\n'; 170, string; 171, string_content; 172, escape_sequence:\n; 173, identifier:m; 174, identifier:metadata; 175, string_content:energy; 176, call; 177, as_pattern_target; 178, attribute; 179, argument_list; 180, as_pattern; 181, call; 182, binary_operator:"[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)) + "\n"; 183, string; 184, string_content; 185, escape_sequence:\n; 186, identifier:open; 187, argument_list; 188, identifier:f; 189, identifier:f; 190, identifier:write; 191, identifier:output; 192, call; 193, as_pattern_target; 194, attribute; 195, argument_list; 196, binary_operator:"[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)); 197, string:"\n"; 198, string_content; 199, escape_sequence:\n; 200, identifier:buf; 201, keyword_argument; 202, identifier:open; 203, argument_list; 204, identifier:f; 205, identifier:f; 206, identifier:write; 207, identifier:output; 208, binary_operator:"[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"; 209, call; 210, escape_sequence:\n; 211, identifier:mode; 212, string; 213, identifier:buf; 214, keyword_argument; 215, string:"[MOLDEN FORMAT]\n"; 216, string:"[N_GEO]\n"; 217, identifier:str; 218, argument_list; 219, string_content:w; 220, identifier:mode; 221, string; 222, call; 223, string_content:x; 224, identifier:len; 225, argument_list; 226, identifier:cartesian_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; 6, 20; 6, 21; 7, 22; 7, 23; 8, 24; 8, 25; 9, 26; 9, 27; 10, 28; 11, 29; 11, 30; 12, 31; 13, 32; 14, 33; 15, 34; 16, 35; 17, 36; 18, 37; 19, 38; 19, 39; 19, 40; 27, 41; 27, 42; 30, 43; 31, 44; 31, 45; 32, 46; 32, 47; 33, 48; 33, 49; 34, 50; 34, 51; 35, 52; 35, 53; 36, 54; 36, 55; 37, 56; 37, 57; 38, 58; 38, 59; 39, 60; 40, 61; 41, 62; 43, 63; 45, 64; 45, 65; 47, 66; 47, 67; 49, 68; 49, 69; 51, 70; 51, 71; 53, 72; 53, 73; 55, 74; 55, 75; 57, 76; 57, 77; 60, 78; 60, 79; 60, 80; 61, 81; 63, 82; 63, 83; 64, 84; 66, 85; 66, 86; 67, 87; 68, 88; 68, 89; 69, 90; 69, 91; 70, 92; 70, 93; 71, 94; 73, 95; 73, 96; 73, 97; 74, 98; 74, 99; 75, 100; 75, 101; 77, 102; 77, 103; 79, 104; 80, 105; 81, 106; 83, 107; 83, 108; 84, 109; 84, 110; 86, 111; 87, 112; 89, 113; 92, 114; 92, 115; 93, 116; 94, 117; 95, 118; 95, 119; 96, 120; 96, 121; 97, 122; 97, 123; 98, 124; 98, 125; 99, 126; 99, 127; 102, 128; 102, 129; 103, 130; 104, 131; 104, 132; 105, 133; 107, 134; 107, 135; 108, 136; 108, 137; 109, 138; 109, 139; 110, 140; 113, 141; 113, 142; 114, 143; 126, 144; 126, 145; 127, 146; 127, 147; 128, 148; 131, 149; 132, 150; 133, 151; 133, 152; 134, 153; 134, 154; 138, 155; 138, 156; 139, 157; 140, 158; 141, 159; 141, 160; 142, 161; 142, 162; 143, 163; 148, 164; 149, 165; 150, 166; 151, 167; 152, 168; 155, 169; 155, 170; 156, 171; 157, 172; 159, 173; 159, 174; 161, 175; 165, 176; 165, 177; 166, 178; 166, 179; 167, 180; 168, 181; 169, 182; 169, 183; 170, 184; 171, 185; 176, 186; 176, 187; 177, 188; 178, 189; 178, 190; 179, 191; 180, 192; 180, 193; 181, 194; 181, 195; 182, 196; 182, 197; 183, 198; 184, 199; 187, 200; 187, 201; 192, 202; 192, 203; 193, 204; 194, 205; 194, 206; 195, 207; 196, 208; 196, 209; 198, 210; 201, 211; 201, 212; 203, 213; 203, 214; 208, 215; 208, 216; 209, 217; 209, 218; 212, 219; 214, 220; 214, 221; 218, 222; 221, 223; 222, 224; 222, 225; 225, 226 | def to_molden(cartesian_list, buf=None, sort_index=True,
overwrite=True, float_format='{:.6f}'.format):
"""Write a list of Cartesians into a molden file.
.. note:: Since it permamently writes a file, this function
is strictly speaking **not sideeffect free**.
The list to be written is of course not changed.
Args:
cartesian_list (list):
buf (str): StringIO-like, optional buffer to write to
sort_index (bool): If sort_index is true, the Cartesian
is sorted by the index before writing.
overwrite (bool): May overwrite existing files.
float_format (one-parameter function): Formatter function
to apply to column’s elements if they are floats.
The result of this function must be a unicode string.
Returns:
formatted : string (or unicode, depending on data and options)
"""
if sort_index:
cartesian_list = [molecule.sort_index() for molecule in cartesian_list]
give_header = ("[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)) + "\n"
+ '[GEOCONV]\n'
+ 'energy\n{energy}'
+ 'max-force\n{max_force}'
+ 'rms-force\n{rms_force}'
+ '[GEOMETRIES] (XYZ)\n').format
values = len(cartesian_list) * '1\n'
energy = [str(m.metadata.get('energy', 1)) for m in cartesian_list]
energy = '\n'.join(energy) + '\n'
header = give_header(energy=energy, max_force=values, rms_force=values)
coordinates = [x.to_xyz(sort_index=sort_index, float_format=float_format)
for x in cartesian_list]
output = header + '\n'.join(coordinates)
if buf is not None:
if overwrite:
with open(buf, mode='w') as f:
f.write(output)
else:
with open(buf, mode='x') as f:
f.write(output)
else:
return output |
0, module; 1, function_definition; 2, function_name:get_inertia; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, function_definition; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, return_statement; 14, comment:"""Calculate the inertia tensor and transforms along
rotation axes.
This function calculates the inertia tensor and returns
a 4-tuple.
The unit is ``amu * length-unit-of-xyz-file**2``
Args:
None
Returns:
dict: The returned dictionary has four possible keys:
``transformed_Cartesian``:
A :class:`~chemcoord.Cartesian`
that is transformed to the basis spanned by
the eigenvectors of the inertia tensor. The x-axis
is the axis with the lowest inertia moment, the
z-axis the one with the highest. Contains also a
column for the mass
``diag_inertia_tensor``:
A vector containing the ascendingly sorted inertia moments after
diagonalization.
``inertia_tensor``:
The inertia tensor in the old basis.
``eigenvectors``:
The eigenvectors of the inertia tensor in the old basis.
Since the inertia_tensor is hermitian, they are orthogonal and
are returned as an orthonormal righthanded basis.
The i-th eigenvector corresponds to the i-th eigenvalue in
``diag_inertia_tensor``.
"""; 15, function_name:calculate_inertia_tensor; 16, parameters; 17, block; 18, assignment; 19, assignment; 20, assignment; 21, assignment; 22, assignment; 23, dictionary; 24, identifier:molecule; 25, expression_statement; 26, expression_statement; 27, expression_statement; 28, expression_statement; 29, expression_statement; 30, expression_statement; 31, expression_statement; 32, return_statement; 33, identifier:molecule; 34, call; 35, identifier:molecule; 36, binary_operator:molecule - molecule.get_barycenter(); 37, pattern_list; 38, call; 39, identifier:eig_v; 40, call; 41, identifier:molecule; 42, call; 43, pair; 44, pair; 45, pair; 46, pair; 47, assignment; 48, assignment; 49, assignment; 50, assignment; 51, assignment; 52, assignment; 53, assignment; 54, expression_list; 55, attribute; 56, argument_list; 57, identifier:molecule; 58, call; 59, identifier:inertia; 60, identifier:eig_v; 61, identifier:diag_inertia; 62, identifier:calculate_inertia_tensor; 63, argument_list; 64, attribute; 65, argument_list; 66, attribute; 67, argument_list; 68, string; 69, identifier:molecule; 70, string; 71, identifier:eig_v; 72, string; 73, identifier:diag_inertia; 74, string; 75, identifier:inertia; 76, identifier:masses; 77, attribute; 78, identifier:pos; 79, attribute; 80, identifier:inertia; 81, call; 82, pattern_list; 83, call; 84, identifier:sorted_index; 85, call; 86, identifier:diag_inertia; 87, subscript; 88, identifier:eig_v; 89, subscript; 90, identifier:inertia; 91, identifier:eig_v; 92, identifier:diag_inertia; 93, identifier:self; 94, identifier:add_data; 95, string; 96, attribute; 97, argument_list; 98, identifier:molecule; 99, identifier:xyz_functions; 100, identifier:orthonormalize_righthanded; 101, identifier:eig_v; 102, identifier:molecule; 103, identifier:basistransform; 104, identifier:eig_v; 105, string_content:transformed_Cartesian; 106, string_content:eigenvectors; 107, string_content:diag_inertia_tensor; 108, string_content:inertia_tensor; 109, subscript; 110, identifier:values; 111, subscript; 112, identifier:values; 113, attribute; 114, argument_list; 115, identifier:diag_inertia; 116, identifier:eig_v; 117, attribute; 118, argument_list; 119, attribute; 120, argument_list; 121, identifier:diag_inertia; 122, identifier:sorted_index; 123, identifier:eig_v; 124, slice; 125, identifier:sorted_index; 126, string_content:mass; 127, identifier:molecule; 128, identifier:get_barycenter; 129, attribute; 130, slice; 131, string; 132, attribute; 133, slice; 134, list; 135, identifier:np; 136, identifier:sum; 137, binary_operator:masses[:, None, None]
* ((pos**2).sum(axis=1)[:, None, None]
* np.identity(3)[None, :, :]
- pos[:, :, None] * pos[:, None, :]); 138, keyword_argument; 139, attribute; 140, identifier:eig; 141, identifier:inertia; 142, identifier:np; 143, identifier:argsort; 144, identifier:diag_inertia; 145, identifier:molecule; 146, identifier:loc; 147, string_content:mass; 148, identifier:molecule; 149, identifier:loc; 150, string; 151, string; 152, string; 153, subscript; 154, parenthesized_expression; 155, identifier:axis; 156, integer:0; 157, identifier:np; 158, identifier:linalg; 159, string_content:x; 160, string_content:y; 161, string_content:z; 162, identifier:masses; 163, slice; 164, None; 165, None; 166, binary_operator:(pos**2).sum(axis=1)[:, None, None]
* np.identity(3)[None, :, :]
- pos[:, :, None] * pos[:, None, :]; 167, binary_operator:(pos**2).sum(axis=1)[:, None, None]
* np.identity(3)[None, :, :]; 168, binary_operator:pos[:, :, None] * pos[:, None, :]; 169, subscript; 170, subscript; 171, subscript; 172, subscript; 173, call; 174, slice; 175, None; 176, None; 177, call; 178, None; 179, slice; 180, slice; 181, identifier:pos; 182, slice; 183, slice; 184, None; 185, identifier:pos; 186, slice; 187, None; 188, slice; 189, attribute; 190, argument_list; 191, attribute; 192, argument_list; 193, parenthesized_expression; 194, identifier:sum; 195, keyword_argument; 196, identifier:np; 197, identifier:identity; 198, integer:3; 199, binary_operator:pos**2; 200, identifier:axis; 201, integer:1; 202, identifier:pos; 203, integer:2 | 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; 7, 16; 7, 17; 8, 18; 9, 19; 10, 20; 11, 21; 12, 22; 13, 23; 16, 24; 17, 25; 17, 26; 17, 27; 17, 28; 17, 29; 17, 30; 17, 31; 17, 32; 18, 33; 18, 34; 19, 35; 19, 36; 20, 37; 20, 38; 21, 39; 21, 40; 22, 41; 22, 42; 23, 43; 23, 44; 23, 45; 23, 46; 25, 47; 26, 48; 27, 49; 28, 50; 29, 51; 30, 52; 31, 53; 32, 54; 34, 55; 34, 56; 36, 57; 36, 58; 37, 59; 37, 60; 37, 61; 38, 62; 38, 63; 40, 64; 40, 65; 42, 66; 42, 67; 43, 68; 43, 69; 44, 70; 44, 71; 45, 72; 45, 73; 46, 74; 46, 75; 47, 76; 47, 77; 48, 78; 48, 79; 49, 80; 49, 81; 50, 82; 50, 83; 51, 84; 51, 85; 52, 86; 52, 87; 53, 88; 53, 89; 54, 90; 54, 91; 54, 92; 55, 93; 55, 94; 56, 95; 58, 96; 58, 97; 63, 98; 64, 99; 64, 100; 65, 101; 66, 102; 66, 103; 67, 104; 68, 105; 70, 106; 72, 107; 74, 108; 77, 109; 77, 110; 79, 111; 79, 112; 81, 113; 81, 114; 82, 115; 82, 116; 83, 117; 83, 118; 85, 119; 85, 120; 87, 121; 87, 122; 89, 123; 89, 124; 89, 125; 95, 126; 96, 127; 96, 128; 109, 129; 109, 130; 109, 131; 111, 132; 111, 133; 111, 134; 113, 135; 113, 136; 114, 137; 114, 138; 117, 139; 117, 140; 118, 141; 119, 142; 119, 143; 120, 144; 129, 145; 129, 146; 131, 147; 132, 148; 132, 149; 134, 150; 134, 151; 134, 152; 137, 153; 137, 154; 138, 155; 138, 156; 139, 157; 139, 158; 150, 159; 151, 160; 152, 161; 153, 162; 153, 163; 153, 164; 153, 165; 154, 166; 166, 167; 166, 168; 167, 169; 167, 170; 168, 171; 168, 172; 169, 173; 169, 174; 169, 175; 169, 176; 170, 177; 170, 178; 170, 179; 170, 180; 171, 181; 171, 182; 171, 183; 171, 184; 172, 185; 172, 186; 172, 187; 172, 188; 173, 189; 173, 190; 177, 191; 177, 192; 189, 193; 189, 194; 190, 195; 191, 196; 191, 197; 192, 198; 193, 199; 195, 200; 195, 201; 199, 202; 199, 203 | def get_inertia(self):
"""Calculate the inertia tensor and transforms along
rotation axes.
This function calculates the inertia tensor and returns
a 4-tuple.
The unit is ``amu * length-unit-of-xyz-file**2``
Args:
None
Returns:
dict: The returned dictionary has four possible keys:
``transformed_Cartesian``:
A :class:`~chemcoord.Cartesian`
that is transformed to the basis spanned by
the eigenvectors of the inertia tensor. The x-axis
is the axis with the lowest inertia moment, the
z-axis the one with the highest. Contains also a
column for the mass
``diag_inertia_tensor``:
A vector containing the ascendingly sorted inertia moments after
diagonalization.
``inertia_tensor``:
The inertia tensor in the old basis.
``eigenvectors``:
The eigenvectors of the inertia tensor in the old basis.
Since the inertia_tensor is hermitian, they are orthogonal and
are returned as an orthonormal righthanded basis.
The i-th eigenvector corresponds to the i-th eigenvalue in
``diag_inertia_tensor``.
"""
def calculate_inertia_tensor(molecule):
masses = molecule.loc[:, 'mass'].values
pos = molecule.loc[:, ['x', 'y', 'z']].values
inertia = np.sum(
masses[:, None, None]
* ((pos**2).sum(axis=1)[:, None, None]
* np.identity(3)[None, :, :]
- pos[:, :, None] * pos[:, None, :]),
axis=0)
diag_inertia, eig_v = np.linalg.eig(inertia)
sorted_index = np.argsort(diag_inertia)
diag_inertia = diag_inertia[sorted_index]
eig_v = eig_v[:, sorted_index]
return inertia, eig_v, diag_inertia
molecule = self.add_data('mass')
molecule = molecule - molecule.get_barycenter()
inertia, eig_v, diag_inertia = calculate_inertia_tensor(molecule)
eig_v = xyz_functions.orthonormalize_righthanded(eig_v)
molecule = molecule.basistransform(eig_v)
return {'transformed_Cartesian': molecule, 'eigenvectors': eig_v,
'diag_inertia_tensor': diag_inertia, 'inertia_tensor': inertia} |
0, module; 1, function_definition; 2, function_name:to_xyz; 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, expression_statement; 13, if_statement; 14, comment:# NOTE the following might be removed in the future; 15, comment:# introduced because of formatting bug in pandas; 16, comment:# See https://github.com/pandas-dev/pandas/issues/13032; 17, expression_statement; 18, expression_statement; 19, if_statement; 20, identifier:buf; 21, None; 22, identifier:sort_index; 23, True; 24, identifier:index; 25, False; 26, identifier:header; 27, False; 28, identifier:float_format; 29, attribute; 30, identifier:overwrite; 31, True; 32, comment:"""Write xyz-file
Args:
buf (str): StringIO-like, optional buffer to write to
sort_index (bool): If sort_index is true, the
:class:`~chemcoord.Cartesian`
is sorted by the index before writing.
float_format (one-parameter function): Formatter function
to apply to column’s elements if they are floats.
The result of this function must be a unicode string.
overwrite (bool): May overwrite existing files.
Returns:
formatted : string (or unicode, depending on data and options)
"""; 33, identifier:sort_index; 34, block; 35, else_clause; 36, assignment; 37, assignment; 38, comparison_operator:buf is not None; 39, block; 40, else_clause; 41, string; 42, identifier:format; 43, expression_statement; 44, block; 45, identifier:space; 46, binary_operator:' ' * (self.loc[:, 'atom'].str.len().max()
- len(self.iloc[0, 0])); 47, identifier:output; 48, call; 49, identifier:buf; 50, None; 51, if_statement; 52, block; 53, string_content:{:.6f}; 54, assignment; 55, expression_statement; 56, string; 57, parenthesized_expression; 58, attribute; 59, argument_list; 60, identifier:overwrite; 61, block; 62, else_clause; 63, return_statement; 64, identifier:molecule_string; 65, call; 66, assignment; 67, string_content:; 68, binary_operator:self.loc[:, 'atom'].str.len().max()
- len(self.iloc[0, 0]); 69, string; 70, identifier:format; 71, keyword_argument; 72, keyword_argument; 73, keyword_argument; 74, keyword_argument; 75, with_statement; 76, block; 77, identifier:output; 78, attribute; 79, argument_list; 80, identifier:molecule_string; 81, call; 82, call; 83, call; 84, string_content; 85, identifier:n; 86, call; 87, identifier:alignment; 88, identifier:space; 89, identifier:frame_string; 90, identifier:molecule_string; 91, identifier:message; 92, string; 93, with_clause; 94, block; 95, with_statement; 96, call; 97, identifier:to_string; 98, keyword_argument; 99, keyword_argument; 100, keyword_argument; 101, attribute; 102, argument_list; 103, attribute; 104, argument_list; 105, identifier:len; 106, argument_list; 107, escape_sequence:\n; 108, escape_sequence:\n; 109, identifier:len; 110, argument_list; 111, string_content:Created by chemcoord http://chemcoord.readthedocs.io/; 112, with_item; 113, expression_statement; 114, with_clause; 115, block; 116, attribute; 117, argument_list; 118, identifier:header; 119, identifier:header; 120, identifier:index; 121, identifier:index; 122, identifier:float_format; 123, identifier:float_format; 124, identifier:self; 125, identifier:to_string; 126, keyword_argument; 127, keyword_argument; 128, keyword_argument; 129, call; 130, identifier:max; 131, subscript; 132, identifier:self; 133, as_pattern; 134, call; 135, with_item; 136, expression_statement; 137, identifier:self; 138, identifier:sort_index; 139, identifier:header; 140, identifier:header; 141, identifier:index; 142, identifier:index; 143, identifier:float_format; 144, identifier:float_format; 145, attribute; 146, argument_list; 147, attribute; 148, integer:0; 149, integer:0; 150, call; 151, as_pattern_target; 152, attribute; 153, argument_list; 154, as_pattern; 155, call; 156, attribute; 157, identifier:len; 158, identifier:self; 159, identifier:iloc; 160, identifier:open; 161, argument_list; 162, identifier:f; 163, identifier:f; 164, identifier:write; 165, identifier:output; 166, call; 167, as_pattern_target; 168, attribute; 169, argument_list; 170, subscript; 171, identifier:str; 172, identifier:buf; 173, keyword_argument; 174, identifier:open; 175, argument_list; 176, identifier:f; 177, identifier:f; 178, identifier:write; 179, identifier:output; 180, attribute; 181, slice; 182, string; 183, identifier:mode; 184, string; 185, identifier:buf; 186, keyword_argument; 187, identifier:self; 188, identifier:loc; 189, string_content:atom; 190, string_content:w; 191, identifier:mode; 192, string; 193, string_content:x | 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; 6, 20; 6, 21; 7, 22; 7, 23; 8, 24; 8, 25; 9, 26; 9, 27; 10, 28; 10, 29; 11, 30; 11, 31; 12, 32; 13, 33; 13, 34; 13, 35; 17, 36; 18, 37; 19, 38; 19, 39; 19, 40; 29, 41; 29, 42; 34, 43; 35, 44; 36, 45; 36, 46; 37, 47; 37, 48; 38, 49; 38, 50; 39, 51; 40, 52; 41, 53; 43, 54; 44, 55; 46, 56; 46, 57; 48, 58; 48, 59; 51, 60; 51, 61; 51, 62; 52, 63; 54, 64; 54, 65; 55, 66; 56, 67; 57, 68; 58, 69; 58, 70; 59, 71; 59, 72; 59, 73; 59, 74; 61, 75; 62, 76; 63, 77; 65, 78; 65, 79; 66, 80; 66, 81; 68, 82; 68, 83; 69, 84; 71, 85; 71, 86; 72, 87; 72, 88; 73, 89; 73, 90; 74, 91; 74, 92; 75, 93; 75, 94; 76, 95; 78, 96; 78, 97; 79, 98; 79, 99; 79, 100; 81, 101; 81, 102; 82, 103; 82, 104; 83, 105; 83, 106; 84, 107; 84, 108; 86, 109; 86, 110; 92, 111; 93, 112; 94, 113; 95, 114; 95, 115; 96, 116; 96, 117; 98, 118; 98, 119; 99, 120; 99, 121; 100, 122; 100, 123; 101, 124; 101, 125; 102, 126; 102, 127; 102, 128; 103, 129; 103, 130; 106, 131; 110, 132; 112, 133; 113, 134; 114, 135; 115, 136; 116, 137; 116, 138; 126, 139; 126, 140; 127, 141; 127, 142; 128, 143; 128, 144; 129, 145; 129, 146; 131, 147; 131, 148; 131, 149; 133, 150; 133, 151; 134, 152; 134, 153; 135, 154; 136, 155; 145, 156; 145, 157; 147, 158; 147, 159; 150, 160; 150, 161; 151, 162; 152, 163; 152, 164; 153, 165; 154, 166; 154, 167; 155, 168; 155, 169; 156, 170; 156, 171; 161, 172; 161, 173; 166, 174; 166, 175; 167, 176; 168, 177; 168, 178; 169, 179; 170, 180; 170, 181; 170, 182; 173, 183; 173, 184; 175, 185; 175, 186; 180, 187; 180, 188; 182, 189; 184, 190; 186, 191; 186, 192; 192, 193 | def to_xyz(self, buf=None, sort_index=True,
index=False, header=False, float_format='{:.6f}'.format,
overwrite=True):
"""Write xyz-file
Args:
buf (str): StringIO-like, optional buffer to write to
sort_index (bool): If sort_index is true, the
:class:`~chemcoord.Cartesian`
is sorted by the index before writing.
float_format (one-parameter function): Formatter function
to apply to column’s elements if they are floats.
The result of this function must be a unicode string.
overwrite (bool): May overwrite existing files.
Returns:
formatted : string (or unicode, depending on data and options)
"""
if sort_index:
molecule_string = self.sort_index().to_string(
header=header, index=index, float_format=float_format)
else:
molecule_string = self.to_string(header=header, index=index,
float_format=float_format)
# NOTE the following might be removed in the future
# introduced because of formatting bug in pandas
# See https://github.com/pandas-dev/pandas/issues/13032
space = ' ' * (self.loc[:, 'atom'].str.len().max()
- len(self.iloc[0, 0]))
output = '{n}\n{message}\n{alignment}{frame_string}'.format(
n=len(self), alignment=space, frame_string=molecule_string,
message='Created by chemcoord http://chemcoord.readthedocs.io/')
if buf is not None:
if overwrite:
with open(buf, mode='w') as f:
f.write(output)
else:
with open(buf, mode='x') as f:
f.write(output)
else:
return output |
0, module; 1, function_definition; 2, function_name:priority; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, comment:# Markers have priority set on the class; 8, if_statement; 9, comment:# Other types have static priority; 10, return_statement; 11, comment:""" Get priority for this Schema.
Used to sort mapping keys
:rtype: int
"""; 12, comparison_operator:self.compiled_type == const.COMPILED_TYPE.MARKER; 13, block; 14, subscript; 15, attribute; 16, attribute; 17, return_statement; 18, attribute; 19, attribute; 20, identifier:self; 21, identifier:compiled_type; 22, attribute; 23, identifier:MARKER; 24, attribute; 25, identifier:const; 26, identifier:compiled_type_priorities; 27, identifier:self; 28, identifier:compiled_type; 29, identifier:const; 30, identifier:COMPILED_TYPE; 31, attribute; 32, identifier:priority; 33, identifier:self; 34, identifier:compiled | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 6, 11; 8, 12; 8, 13; 10, 14; 12, 15; 12, 16; 13, 17; 14, 18; 14, 19; 15, 20; 15, 21; 16, 22; 16, 23; 17, 24; 18, 25; 18, 26; 19, 27; 19, 28; 22, 29; 22, 30; 24, 31; 24, 32; 31, 33; 31, 34 | def priority(self):
""" Get priority for this Schema.
Used to sort mapping keys
:rtype: int
"""
# Markers have priority set on the class
if self.compiled_type == const.COMPILED_TYPE.MARKER:
return self.compiled.priority
# Other types have static priority
return const.compiled_type_priorities[self.compiled_type] |
0, module; 1, function_definition; 2, function_name:sort_schemas; 3, parameters; 4, block; 5, identifier:cls; 6, identifier:schemas_list; 7, expression_statement; 8, return_statement; 9, comment:""" Sort the provided list of schemas according to their priority.
This also supports markers, and markers of a single type are also sorted according to the priority of the wrapped schema.
:type schemas_list: list[CompiledSchema]
:rtype: list[CompiledSchema]
"""; 10, call; 11, identifier:sorted; 12, argument_list; 13, identifier:schemas_list; 14, keyword_argument; 15, keyword_argument; 16, identifier:key; 17, lambda; 18, identifier:reverse; 19, True; 20, lambda_parameters; 21, tuple; 22, identifier:x; 23, comment:# Top-level priority:; 24, comment:# priority of the schema itself; 25, attribute; 26, comment:# Second-level priority (for markers of the common type); 27, comment:# This ensures that Optional(1) always goes before Optional(int); 28, conditional_expression:x.compiled.key_schema.priority if x.compiled_type == const.COMPILED_TYPE.MARKER else 0; 29, identifier:x; 30, identifier:priority; 31, attribute; 32, comparison_operator:x.compiled_type == const.COMPILED_TYPE.MARKER; 33, integer:0; 34, attribute; 35, identifier:priority; 36, attribute; 37, attribute; 38, attribute; 39, identifier:key_schema; 40, identifier:x; 41, identifier:compiled_type; 42, attribute; 43, identifier:MARKER; 44, identifier:x; 45, identifier:compiled; 46, identifier:const; 47, identifier:COMPILED_TYPE | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 7, 9; 8, 10; 10, 11; 10, 12; 12, 13; 12, 14; 12, 15; 14, 16; 14, 17; 15, 18; 15, 19; 17, 20; 17, 21; 20, 22; 21, 23; 21, 24; 21, 25; 21, 26; 21, 27; 21, 28; 25, 29; 25, 30; 28, 31; 28, 32; 28, 33; 31, 34; 31, 35; 32, 36; 32, 37; 34, 38; 34, 39; 36, 40; 36, 41; 37, 42; 37, 43; 38, 44; 38, 45; 42, 46; 42, 47 | def sort_schemas(cls, schemas_list):
""" Sort the provided list of schemas according to their priority.
This also supports markers, and markers of a single type are also sorted according to the priority of the wrapped schema.
:type schemas_list: list[CompiledSchema]
:rtype: list[CompiledSchema]
"""
return sorted(schemas_list,
key=lambda x: (
# Top-level priority:
# priority of the schema itself
x.priority,
# Second-level priority (for markers of the common type)
# This ensures that Optional(1) always goes before Optional(int)
x.compiled.key_schema.priority if x.compiled_type == const.COMPILED_TYPE.MARKER else 0
), reverse=True) |
0, module; 1, function_definition; 2, function_name:patch_cursor; 3, parameters; 4, block; 5, identifier:cursor; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, dictionary_splat_pattern; 11, expression_statement; 12, if_statement; 13, if_statement; 14, if_statement; 15, if_statement; 16, identifier:batch_size; 17, None; 18, identifier:limit; 19, None; 20, identifier:skip; 21, None; 22, identifier:sort; 23, None; 24, identifier:kwargs; 25, comment:"""
Adds batch_size, limit, sort parameters to a DB cursor
"""; 26, comparison_operator:type(batch_size) == int; 27, block; 28, comparison_operator:limit is not None; 29, block; 30, comparison_operator:sort is not None; 31, block; 32, comparison_operator:skip is not None; 33, block; 34, call; 35, identifier:int; 36, expression_statement; 37, identifier:limit; 38, None; 39, expression_statement; 40, identifier:sort; 41, None; 42, expression_statement; 43, identifier:skip; 44, None; 45, expression_statement; 46, identifier:type; 47, argument_list; 48, call; 49, call; 50, call; 51, call; 52, identifier:batch_size; 53, attribute; 54, argument_list; 55, attribute; 56, argument_list; 57, attribute; 58, argument_list; 59, attribute; 60, argument_list; 61, identifier:cursor; 62, identifier:batch_size; 63, identifier:batch_size; 64, identifier:cursor; 65, identifier:limit; 66, identifier:limit; 67, identifier:cursor; 68, identifier:sort; 69, identifier:sort; 70, identifier:cursor; 71, identifier:skip; 72, identifier:skip | 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; 6, 16; 6, 17; 7, 18; 7, 19; 8, 20; 8, 21; 9, 22; 9, 23; 10, 24; 11, 25; 12, 26; 12, 27; 13, 28; 13, 29; 14, 30; 14, 31; 15, 32; 15, 33; 26, 34; 26, 35; 27, 36; 28, 37; 28, 38; 29, 39; 30, 40; 30, 41; 31, 42; 32, 43; 32, 44; 33, 45; 34, 46; 34, 47; 36, 48; 39, 49; 42, 50; 45, 51; 47, 52; 48, 53; 48, 54; 49, 55; 49, 56; 50, 57; 50, 58; 51, 59; 51, 60; 53, 61; 53, 62; 54, 63; 55, 64; 55, 65; 56, 66; 57, 67; 57, 68; 58, 69; 59, 70; 59, 71; 60, 72 | def patch_cursor(cursor, batch_size=None, limit=None, skip=None, sort=None, **kwargs):
"""
Adds batch_size, limit, sort parameters to a DB cursor
"""
if type(batch_size) == int:
cursor.batch_size(batch_size)
if limit is not None:
cursor.limit(limit)
if sort is not None:
cursor.sort(sort)
if skip is not None:
cursor.skip(skip) |
0, module; 1, function_definition; 2, function_name:add_interval; 3, parameters; 4, block; 5, identifier:self; 6, identifier:start; 7, identifier:end; 8, default_parameter; 9, expression_statement; 10, comment:# Ignore intervals of 0 or negative length; 11, if_statement; 12, if_statement; 13, identifier:data; 14, None; 15, string:'''
Inserts an interval to the tree.
Note that when inserting we do not maintain appropriate sorting of the "mid" data structure.
This should be done after all intervals are inserted.
'''; 16, comparison_operator:(end - start) <= 0; 17, block; 18, comparison_operator:self.single_interval is None; 19, comment:# This is an empty tree and we are adding the first interval. Just record it in a field.; 20, block; 21, elif_clause; 22, else_clause; 23, parenthesized_expression; 24, integer:0; 25, return_statement; 26, attribute; 27, None; 28, expression_statement; 29, comparison_operator:self.single_interval == 0; 30, comment:# This is a usual tree, use standard addition method; 31, block; 32, comment:# This is a tree with a single interval. Convert to a usual tree.; 33, block; 34, binary_operator:end - start; 35, identifier:self; 36, identifier:single_interval; 37, assignment; 38, attribute; 39, integer:0; 40, expression_statement; 41, expression_statement; 42, expression_statement; 43, expression_statement; 44, identifier:end; 45, identifier:start; 46, attribute; 47, tuple; 48, identifier:self; 49, identifier:single_interval; 50, call; 51, call; 52, assignment; 53, call; 54, identifier:self; 55, identifier:single_interval; 56, identifier:start; 57, identifier:end; 58, identifier:data; 59, attribute; 60, argument_list; 61, attribute; 62, argument_list; 63, attribute; 64, integer:0; 65, attribute; 66, argument_list; 67, identifier:self; 68, identifier:_add_interval; 69, identifier:start; 70, identifier:end; 71, identifier:data; 72, identifier:self; 73, identifier:_add_interval; 74, list_splat; 75, identifier:self; 76, identifier:single_interval; 77, identifier:self; 78, identifier:_add_interval; 79, identifier:start; 80, identifier:end; 81, identifier:data; 82, attribute; 83, identifier:self; 84, identifier:single_interval | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 8, 13; 8, 14; 9, 15; 11, 16; 11, 17; 12, 18; 12, 19; 12, 20; 12, 21; 12, 22; 16, 23; 16, 24; 17, 25; 18, 26; 18, 27; 20, 28; 21, 29; 21, 30; 21, 31; 22, 32; 22, 33; 23, 34; 26, 35; 26, 36; 28, 37; 29, 38; 29, 39; 31, 40; 33, 41; 33, 42; 33, 43; 34, 44; 34, 45; 37, 46; 37, 47; 38, 48; 38, 49; 40, 50; 41, 51; 42, 52; 43, 53; 46, 54; 46, 55; 47, 56; 47, 57; 47, 58; 50, 59; 50, 60; 51, 61; 51, 62; 52, 63; 52, 64; 53, 65; 53, 66; 59, 67; 59, 68; 60, 69; 60, 70; 60, 71; 61, 72; 61, 73; 62, 74; 63, 75; 63, 76; 65, 77; 65, 78; 66, 79; 66, 80; 66, 81; 74, 82; 82, 83; 82, 84 | def add_interval(self, start, end, data=None):
'''
Inserts an interval to the tree.
Note that when inserting we do not maintain appropriate sorting of the "mid" data structure.
This should be done after all intervals are inserted.
'''
# Ignore intervals of 0 or negative length
if (end - start) <= 0:
return
if self.single_interval is None:
# This is an empty tree and we are adding the first interval. Just record it in a field.
self.single_interval = (start, end, data)
elif self.single_interval == 0:
# This is a usual tree, use standard addition method
self._add_interval(start, end, data)
else:
# This is a tree with a single interval. Convert to a usual tree.
self._add_interval(*self.single_interval)
self.single_interval = 0
self._add_interval(start, end, data) |
0, module; 1, function_definition; 2, function_name:parse; 3, parameters; 4, block; 5, identifier:cls; 6, identifier:querydict; 7, expression_statement; 8, for_statement; 9, expression_statement; 10, return_statement; 11, comment:""" Parse querydict data.
There are expected agruments:
distinct, fields, filter, include, page, sort
Parameters
----------
querydict : django.http.request.QueryDict
MultiValueDict with query arguments.
Returns
-------
result : dict
dictionary in format {key: value}.
Raises
------
ValueError
If args consist of not know key.
"""; 12, identifier:key; 13, call; 14, block; 15, assignment; 16, identifier:result; 17, attribute; 18, argument_list; 19, if_statement; 20, identifier:result; 21, call; 22, identifier:querydict; 23, identifier:keys; 24, not_operator; 25, block; 26, identifier:JSONAPIQueryDict; 27, argument_list; 28, call; 29, expression_statement; 30, raise_statement; 31, keyword_argument; 32, keyword_argument; 33, keyword_argument; 34, keyword_argument; 35, keyword_argument; 36, keyword_argument; 37, identifier:any; 38, argument_list; 39, assignment; 40, call; 41, identifier:distinct; 42, call; 43, identifier:fields; 44, call; 45, identifier:filter; 46, call; 47, identifier:include; 48, call; 49, identifier:page; 50, conditional_expression:int(querydict.get('page')) if querydict.get('page') else None; 51, identifier:sort; 52, call; 53, tuple; 54, identifier:msg; 55, call; 56, identifier:ValueError; 57, argument_list; 58, attribute; 59, argument_list; 60, attribute; 61, argument_list; 62, attribute; 63, argument_list; 64, attribute; 65, argument_list; 66, call; 67, call; 68, None; 69, attribute; 70, argument_list; 71, comparison_operator:key in JSONAPIQueryDict._fields; 72, call; 73, attribute; 74, argument_list; 75, identifier:msg; 76, identifier:cls; 77, identifier:prepare_values; 78, call; 79, identifier:cls; 80, identifier:parse_fields; 81, identifier:querydict; 82, identifier:querydict; 83, identifier:getlist; 84, string; 85, identifier:cls; 86, identifier:prepare_values; 87, call; 88, identifier:int; 89, argument_list; 90, attribute; 91, argument_list; 92, identifier:cls; 93, identifier:prepare_values; 94, call; 95, identifier:key; 96, attribute; 97, attribute; 98, argument_list; 99, string:"Query parameter {} is not known"; 100, identifier:format; 101, identifier:key; 102, attribute; 103, argument_list; 104, string_content:filter; 105, attribute; 106, argument_list; 107, call; 108, identifier:querydict; 109, identifier:get; 110, string; 111, attribute; 112, argument_list; 113, identifier:JSONAPIQueryDict; 114, identifier:_fields; 115, attribute; 116, identifier:match; 117, identifier:key; 118, identifier:querydict; 119, identifier:getlist; 120, string; 121, identifier:querydict; 122, identifier:getlist; 123, string; 124, attribute; 125, argument_list; 126, string_content:page; 127, identifier:querydict; 128, identifier:getlist; 129, string; 130, identifier:cls; 131, identifier:RE_FIELDS; 132, string_content:distinct; 133, string_content:include; 134, identifier:querydict; 135, identifier:get; 136, string; 137, string_content:sort; 138, string_content:page | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 8, 13; 8, 14; 9, 15; 10, 16; 13, 17; 13, 18; 14, 19; 15, 20; 15, 21; 17, 22; 17, 23; 19, 24; 19, 25; 21, 26; 21, 27; 24, 28; 25, 29; 25, 30; 27, 31; 27, 32; 27, 33; 27, 34; 27, 35; 27, 36; 28, 37; 28, 38; 29, 39; 30, 40; 31, 41; 31, 42; 32, 43; 32, 44; 33, 45; 33, 46; 34, 47; 34, 48; 35, 49; 35, 50; 36, 51; 36, 52; 38, 53; 39, 54; 39, 55; 40, 56; 40, 57; 42, 58; 42, 59; 44, 60; 44, 61; 46, 62; 46, 63; 48, 64; 48, 65; 50, 66; 50, 67; 50, 68; 52, 69; 52, 70; 53, 71; 53, 72; 55, 73; 55, 74; 57, 75; 58, 76; 58, 77; 59, 78; 60, 79; 60, 80; 61, 81; 62, 82; 62, 83; 63, 84; 64, 85; 64, 86; 65, 87; 66, 88; 66, 89; 67, 90; 67, 91; 69, 92; 69, 93; 70, 94; 71, 95; 71, 96; 72, 97; 72, 98; 73, 99; 73, 100; 74, 101; 78, 102; 78, 103; 84, 104; 87, 105; 87, 106; 89, 107; 90, 108; 90, 109; 91, 110; 94, 111; 94, 112; 96, 113; 96, 114; 97, 115; 97, 116; 98, 117; 102, 118; 102, 119; 103, 120; 105, 121; 105, 122; 106, 123; 107, 124; 107, 125; 110, 126; 111, 127; 111, 128; 112, 129; 115, 130; 115, 131; 120, 132; 123, 133; 124, 134; 124, 135; 125, 136; 129, 137; 136, 138 | def parse(cls, querydict):
""" Parse querydict data.
There are expected agruments:
distinct, fields, filter, include, page, sort
Parameters
----------
querydict : django.http.request.QueryDict
MultiValueDict with query arguments.
Returns
-------
result : dict
dictionary in format {key: value}.
Raises
------
ValueError
If args consist of not know key.
"""
for key in querydict.keys():
if not any((key in JSONAPIQueryDict._fields,
cls.RE_FIELDS.match(key))):
msg = "Query parameter {} is not known".format(key)
raise ValueError(msg)
result = JSONAPIQueryDict(
distinct=cls.prepare_values(querydict.getlist('distinct')),
fields=cls.parse_fields(querydict),
filter=querydict.getlist('filter'),
include=cls.prepare_values(querydict.getlist('include')),
page=int(querydict.get('page')) if querydict.get('page') else None,
sort=cls.prepare_values(querydict.getlist('sort'))
)
return result |
0, module; 1, function_definition; 2, function_name:_pcca_connected_isa; 3, parameters; 4, block; 5, identifier:evec; 6, identifier:n_clusters; 7, expression_statement; 8, expression_statement; 9, comment:# do we have enough eigenvectors?; 10, if_statement; 11, comment:# check if the first, and only the first eigenvector is constant; 12, expression_statement; 13, assert_statement; 14, assert_statement; 15, comment:# local copy of the eigenvectors; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, comment:# representative states; 20, expression_statement; 21, comment:# select the first representative as the most outlying point; 22, for_statement; 23, comment:# translate coordinates to make the first representative the origin; 24, expression_statement; 25, comment:# select the other m-1 representatives using a Gram-Schmidt orthogonalization; 26, for_statement; 27, comment:# print "Final selection ", ind; 28, comment:# obtain transformation matrix of eigenvectors to membership matrix; 29, expression_statement; 30, comment:#print "Rotation matrix \n ", rot_mat; 31, comment:# compute membership matrix; 32, expression_statement; 33, comment:#print "chi \n ", chi; 34, return_statement; 35, comment:"""
PCCA+ spectral clustering method using the inner simplex algorithm.
Clusters the first n_cluster eigenvectors of a transition matrix in order to cluster the states.
This function assumes that the state space is fully connected, i.e. the transition matrix whose
eigenvectors are used is supposed to have only one eigenvalue 1, and the corresponding first
eigenvector (evec[:,0]) must be constant.
Parameters
----------
eigenvectors : ndarray
A matrix with the sorted eigenvectors in the columns. The stationary eigenvector should
be first, then the one to the slowest relaxation process, etc.
n_clusters : int
Number of clusters to group to.
Returns
-------
(chi, rot_mat)
chi : ndarray (n x m)
A matrix containing the probability or membership of each state to be assigned to each cluster.
The rows sum to 1.
rot_mat : ndarray (m x m)
A rotation matrix that rotates the dominant eigenvectors to yield the PCCA memberships, i.e.:
chi = np.dot(evec, rot_matrix
References
----------
[1] P. Deuflhard and M. Weber, Robust Perron cluster analysis in conformation dynamics.
in: Linear Algebra Appl. 398C M. Dellnitz and S. Kirkland and M. Neumann and C. Schuette (Editors)
Elsevier, New York, 2005, pp. 161-184
"""; 36, assignment; 37, comparison_operator:n_clusters > m; 38, block; 39, assignment; 40, comparison_operator:diffs[0] < 1e-6; 41, concatenated_string; 42, comparison_operator:diffs[1] > 1e-6; 43, concatenated_string; 44, assignment; 45, assignment; 46, assignment; 47, assignment; 48, tuple_pattern; 49, call; 50, block; 51, augmented_assignment; 52, identifier:k; 53, call; 54, block; 55, assignment; 56, assignment; 57, tuple; 58, tuple_pattern; 59, attribute; 60, identifier:n_clusters; 61, identifier:m; 62, raise_statement; 63, identifier:diffs; 64, call; 65, subscript; 66, float:1e-6; 67, string:"First eigenvector is not constant. This indicates that the transition matrix "; 68, string:"is not connected or the eigenvectors are incorrectly sorted. Cannot do PCCA."; 69, subscript; 70, float:1e-6; 71, string:"An eigenvector after the first one is constant. "; 72, string:"Probably the eigenvectors are incorrectly sorted. Cannot do PCCA."; 73, identifier:c; 74, subscript; 75, identifier:ortho_sys; 76, call; 77, identifier:max_dist; 78, float:0.0; 79, identifier:ind; 80, call; 81, identifier:i; 82, identifier:row; 83, identifier:enumerate; 84, argument_list; 85, if_statement; 86, identifier:ortho_sys; 87, subscript; 88, identifier:range; 89, argument_list; 90, expression_statement; 91, expression_statement; 92, comment:# select next farthest point that is not yet a representative; 93, for_statement; 94, expression_statement; 95, identifier:rot_mat; 96, call; 97, identifier:chi; 98, call; 99, identifier:chi; 100, identifier:rot_mat; 101, identifier:n; 102, identifier:m; 103, identifier:evec; 104, identifier:shape; 105, call; 106, attribute; 107, argument_list; 108, identifier:diffs; 109, integer:0; 110, identifier:diffs; 111, integer:1; 112, identifier:evec; 113, slice; 114, call; 115, attribute; 116, argument_list; 117, attribute; 118, argument_list; 119, identifier:c; 120, comparison_operator:np.linalg.norm(row, 2) > max_dist; 121, block; 122, identifier:c; 123, subscript; 124, None; 125, integer:1; 126, identifier:n_clusters; 127, assignment; 128, assignment; 129, tuple_pattern; 130, call; 131, block; 132, augmented_assignment; 133, attribute; 134, argument_list; 135, attribute; 136, argument_list; 137, identifier:ValueError; 138, argument_list; 139, identifier:np; 140, identifier:abs; 141, binary_operator:np.max(evec, axis=0) - np.min(evec, axis=0); 142, identifier:list; 143, argument_list; 144, identifier:np; 145, identifier:copy; 146, identifier:c; 147, identifier:np; 148, identifier:zeros; 149, identifier:n_clusters; 150, keyword_argument; 151, call; 152, identifier:max_dist; 153, expression_statement; 154, expression_statement; 155, identifier:ind; 156, integer:0; 157, identifier:max_dist; 158, float:0.0; 159, identifier:temp; 160, call; 161, identifier:i; 162, identifier:row; 163, identifier:enumerate; 164, argument_list; 165, expression_statement; 166, expression_statement; 167, if_statement; 168, identifier:ortho_sys; 169, call; 170, attribute; 171, identifier:inv; 172, subscript; 173, identifier:np; 174, identifier:dot; 175, identifier:c; 176, identifier:rot_mat; 177, binary_operator:"Cannot cluster the (" + str(n) + " x " + str(m)
+ " eigenvector matrix to " + str(n_clusters) + " clusters."; 178, call; 179, call; 180, call; 181, identifier:dtype; 182, attribute; 183, attribute; 184, argument_list; 185, assignment; 186, assignment; 187, attribute; 188, argument_list; 189, identifier:ortho_sys; 190, augmented_assignment; 191, assignment; 192, boolean_operator; 193, block; 194, attribute; 195, argument_list; 196, identifier:np; 197, identifier:linalg; 198, identifier:c; 199, identifier:ind; 200, binary_operator:"Cannot cluster the (" + str(n) + " x " + str(m)
+ " eigenvector matrix to " + str(n_clusters); 201, string:" clusters."; 202, attribute; 203, argument_list; 204, attribute; 205, argument_list; 206, identifier:range; 207, argument_list; 208, identifier:np; 209, identifier:int32; 210, attribute; 211, identifier:norm; 212, identifier:row; 213, integer:2; 214, identifier:max_dist; 215, call; 216, subscript; 217, identifier:i; 218, identifier:np; 219, identifier:copy; 220, subscript; 221, identifier:row; 222, call; 223, identifier:distt; 224, call; 225, comparison_operator:distt > max_dist; 226, comparison_operator:i not in ind[0:k]; 227, expression_statement; 228, expression_statement; 229, attribute; 230, identifier:norm; 231, subscript; 232, integer:2; 233, binary_operator:"Cannot cluster the (" + str(n) + " x " + str(m)
+ " eigenvector matrix to "; 234, call; 235, identifier:np; 236, identifier:max; 237, identifier:evec; 238, keyword_argument; 239, identifier:np; 240, identifier:min; 241, identifier:evec; 242, keyword_argument; 243, identifier:n_clusters; 244, identifier:np; 245, identifier:linalg; 246, attribute; 247, argument_list; 248, identifier:ind; 249, integer:0; 250, identifier:ortho_sys; 251, subscript; 252, attribute; 253, argument_list; 254, attribute; 255, argument_list; 256, identifier:distt; 257, identifier:max_dist; 258, identifier:i; 259, subscript; 260, assignment; 261, assignment; 262, identifier:np; 263, identifier:linalg; 264, identifier:ortho_sys; 265, subscript; 266, binary_operator:"Cannot cluster the (" + str(n) + " x " + str(m); 267, string:" eigenvector matrix to "; 268, identifier:str; 269, argument_list; 270, identifier:axis; 271, integer:0; 272, identifier:axis; 273, integer:0; 274, attribute; 275, identifier:norm; 276, identifier:row; 277, integer:2; 278, identifier:ind; 279, binary_operator:k - 1; 280, identifier:np; 281, identifier:dot; 282, call; 283, identifier:temp; 284, attribute; 285, identifier:norm; 286, identifier:row; 287, integer:2; 288, identifier:ind; 289, slice; 290, identifier:max_dist; 291, identifier:distt; 292, subscript; 293, identifier:i; 294, identifier:ind; 295, identifier:k; 296, binary_operator:"Cannot cluster the (" + str(n) + " x "; 297, call; 298, identifier:n_clusters; 299, identifier:np; 300, identifier:linalg; 301, identifier:k; 302, integer:1; 303, attribute; 304, argument_list; 305, identifier:np; 306, identifier:linalg; 307, integer:0; 308, identifier:k; 309, identifier:ind; 310, identifier:k; 311, binary_operator:"Cannot cluster the (" + str(n); 312, string:" x "; 313, identifier:str; 314, argument_list; 315, identifier:np; 316, identifier:dot; 317, identifier:temp; 318, call; 319, string:"Cannot cluster the ("; 320, call; 321, identifier:m; 322, attribute; 323, argument_list; 324, identifier:str; 325, argument_list; 326, identifier:np; 327, identifier:transpose; 328, identifier:row; 329, 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; 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; 7, 35; 8, 36; 10, 37; 10, 38; 12, 39; 13, 40; 13, 41; 14, 42; 14, 43; 16, 44; 17, 45; 18, 46; 20, 47; 22, 48; 22, 49; 22, 50; 24, 51; 26, 52; 26, 53; 26, 54; 29, 55; 32, 56; 34, 57; 36, 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; 46, 77; 46, 78; 47, 79; 47, 80; 48, 81; 48, 82; 49, 83; 49, 84; 50, 85; 51, 86; 51, 87; 53, 88; 53, 89; 54, 90; 54, 91; 54, 92; 54, 93; 54, 94; 55, 95; 55, 96; 56, 97; 56, 98; 57, 99; 57, 100; 58, 101; 58, 102; 59, 103; 59, 104; 62, 105; 64, 106; 64, 107; 65, 108; 65, 109; 69, 110; 69, 111; 74, 112; 74, 113; 74, 114; 76, 115; 76, 116; 80, 117; 80, 118; 84, 119; 85, 120; 85, 121; 87, 122; 87, 123; 87, 124; 89, 125; 89, 126; 90, 127; 91, 128; 93, 129; 93, 130; 93, 131; 94, 132; 96, 133; 96, 134; 98, 135; 98, 136; 105, 137; 105, 138; 106, 139; 106, 140; 107, 141; 114, 142; 114, 143; 115, 144; 115, 145; 116, 146; 117, 147; 117, 148; 118, 149; 118, 150; 120, 151; 120, 152; 121, 153; 121, 154; 123, 155; 123, 156; 127, 157; 127, 158; 128, 159; 128, 160; 129, 161; 129, 162; 130, 163; 130, 164; 131, 165; 131, 166; 131, 167; 132, 168; 132, 169; 133, 170; 133, 171; 134, 172; 135, 173; 135, 174; 136, 175; 136, 176; 138, 177; 141, 178; 141, 179; 143, 180; 150, 181; 150, 182; 151, 183; 151, 184; 153, 185; 154, 186; 160, 187; 160, 188; 164, 189; 165, 190; 166, 191; 167, 192; 167, 193; 169, 194; 169, 195; 170, 196; 170, 197; 172, 198; 172, 199; 177, 200; 177, 201; 178, 202; 178, 203; 179, 204; 179, 205; 180, 206; 180, 207; 182, 208; 182, 209; 183, 210; 183, 211; 184, 212; 184, 213; 185, 214; 185, 215; 186, 216; 186, 217; 187, 218; 187, 219; 188, 220; 190, 221; 190, 222; 191, 223; 191, 224; 192, 225; 192, 226; 193, 227; 193, 228; 194, 229; 194, 230; 195, 231; 195, 232; 200, 233; 200, 234; 202, 235; 202, 236; 203, 237; 203, 238; 204, 239; 204, 240; 205, 241; 205, 242; 207, 243; 210, 244; 210, 245; 215, 246; 215, 247; 216, 248; 216, 249; 220, 250; 220, 251; 222, 252; 222, 253; 224, 254; 224, 255; 225, 256; 225, 257; 226, 258; 226, 259; 227, 260; 228, 261; 229, 262; 229, 263; 231, 264; 231, 265; 233, 266; 233, 267; 234, 268; 234, 269; 238, 270; 238, 271; 242, 272; 242, 273; 246, 274; 246, 275; 247, 276; 247, 277; 251, 278; 251, 279; 252, 280; 252, 281; 253, 282; 253, 283; 254, 284; 254, 285; 255, 286; 255, 287; 259, 288; 259, 289; 260, 290; 260, 291; 261, 292; 261, 293; 265, 294; 265, 295; 266, 296; 266, 297; 269, 298; 274, 299; 274, 300; 279, 301; 279, 302; 282, 303; 282, 304; 284, 305; 284, 306; 289, 307; 289, 308; 292, 309; 292, 310; 296, 311; 296, 312; 297, 313; 297, 314; 303, 315; 303, 316; 304, 317; 304, 318; 311, 319; 311, 320; 314, 321; 318, 322; 318, 323; 320, 324; 320, 325; 322, 326; 322, 327; 323, 328; 325, 329 | def _pcca_connected_isa(evec, n_clusters):
"""
PCCA+ spectral clustering method using the inner simplex algorithm.
Clusters the first n_cluster eigenvectors of a transition matrix in order to cluster the states.
This function assumes that the state space is fully connected, i.e. the transition matrix whose
eigenvectors are used is supposed to have only one eigenvalue 1, and the corresponding first
eigenvector (evec[:,0]) must be constant.
Parameters
----------
eigenvectors : ndarray
A matrix with the sorted eigenvectors in the columns. The stationary eigenvector should
be first, then the one to the slowest relaxation process, etc.
n_clusters : int
Number of clusters to group to.
Returns
-------
(chi, rot_mat)
chi : ndarray (n x m)
A matrix containing the probability or membership of each state to be assigned to each cluster.
The rows sum to 1.
rot_mat : ndarray (m x m)
A rotation matrix that rotates the dominant eigenvectors to yield the PCCA memberships, i.e.:
chi = np.dot(evec, rot_matrix
References
----------
[1] P. Deuflhard and M. Weber, Robust Perron cluster analysis in conformation dynamics.
in: Linear Algebra Appl. 398C M. Dellnitz and S. Kirkland and M. Neumann and C. Schuette (Editors)
Elsevier, New York, 2005, pp. 161-184
"""
(n, m) = evec.shape
# do we have enough eigenvectors?
if n_clusters > m:
raise ValueError("Cannot cluster the (" + str(n) + " x " + str(m)
+ " eigenvector matrix to " + str(n_clusters) + " clusters.")
# check if the first, and only the first eigenvector is constant
diffs = np.abs(np.max(evec, axis=0) - np.min(evec, axis=0))
assert diffs[0] < 1e-6, "First eigenvector is not constant. This indicates that the transition matrix " \
"is not connected or the eigenvectors are incorrectly sorted. Cannot do PCCA."
assert diffs[1] > 1e-6, "An eigenvector after the first one is constant. " \
"Probably the eigenvectors are incorrectly sorted. Cannot do PCCA."
# local copy of the eigenvectors
c = evec[:, list(range(n_clusters))]
ortho_sys = np.copy(c)
max_dist = 0.0
# representative states
ind = np.zeros(n_clusters, dtype=np.int32)
# select the first representative as the most outlying point
for (i, row) in enumerate(c):
if np.linalg.norm(row, 2) > max_dist:
max_dist = np.linalg.norm(row, 2)
ind[0] = i
# translate coordinates to make the first representative the origin
ortho_sys -= c[ind[0], None]
# select the other m-1 representatives using a Gram-Schmidt orthogonalization
for k in range(1, n_clusters):
max_dist = 0.0
temp = np.copy(ortho_sys[ind[k - 1]])
# select next farthest point that is not yet a representative
for (i, row) in enumerate(ortho_sys):
row -= np.dot(np.dot(temp, np.transpose(row)), temp)
distt = np.linalg.norm(row, 2)
if distt > max_dist and i not in ind[0:k]:
max_dist = distt
ind[k] = i
ortho_sys /= np.linalg.norm(ortho_sys[ind[k]], 2)
# print "Final selection ", ind
# obtain transformation matrix of eigenvectors to membership matrix
rot_mat = np.linalg.inv(c[ind])
#print "Rotation matrix \n ", rot_mat
# compute membership matrix
chi = np.dot(c, rot_mat)
#print "chi \n ", chi
return (chi, rot_mat) |
0, module; 1, function_definition; 2, function_name:_opt_soft; 3, parameters; 4, block; 5, identifier:eigvectors; 6, identifier:rot_matrix; 7, identifier:n_clusters; 8, expression_statement; 9, comment:# only consider first n_clusters eigenvectors; 10, expression_statement; 11, comment:# crop first row and first column from rot_matrix; 12, comment:# rot_crop_matrix = rot_matrix[1:,1:]; 13, expression_statement; 14, expression_statement; 15, comment:# reshape rot_crop_matrix into linear vector; 16, expression_statement; 17, comment:# Susanna Roeblitz' target function for optimization; 18, function_definition; 19, import_from_statement; 20, expression_statement; 21, expression_statement; 22, expression_statement; 23, return_statement; 24, comment:"""
Optimizes the PCCA+ rotation matrix such that the memberships are exclusively nonnegative.
Parameters
----------
eigenvectors : ndarray
A matrix with the sorted eigenvectors in the columns. The stationary eigenvector should
be first, then the one to the slowest relaxation process, etc.
rot_mat : ndarray (m x m)
nonoptimized rotation matrix
n_clusters : int
Number of clusters to group to.
Returns
-------
rot_mat : ndarray (m x m)
Optimized rotation matrix that rotates the dominant eigenvectors to yield the PCCA memberships, i.e.:
chi = np.dot(evec, rot_matrix
References
----------
[1] S. Roeblitz and M. Weber, Fuzzy spectral clustering by PCCA+:
application to Markov state models and data classification.
Adv Data Anal Classif 7, 147-179 (2013).
"""; 25, assignment; 26, assignment; 27, assignment; 28, assignment; 29, function_name:susanna_func; 30, parameters; 31, comment:# reshape into matrix; 32, block; 33, dotted_name; 34, dotted_name; 35, assignment; 36, assignment; 37, assignment; 38, identifier:rot_matrix; 39, identifier:eigvectors; 40, subscript; 41, identifier:rot_crop_matrix; 42, subscript; 43, tuple_pattern; 44, attribute; 45, identifier:rot_crop_vec; 46, call; 47, identifier:rot_crop_vec; 48, identifier:eigvectors; 49, expression_statement; 50, comment:# fill matrix; 51, expression_statement; 52, expression_statement; 53, for_statement; 54, return_statement; 55, identifier:scipy; 56, identifier:optimize; 57, identifier:fmin; 58, identifier:rot_crop_vec_opt; 59, call; 60, identifier:rot_crop_matrix; 61, call; 62, identifier:rot_matrix; 63, call; 64, identifier:eigvectors; 65, slice; 66, slice; 67, subscript; 68, slice; 69, slice; 70, identifier:x; 71, identifier:y; 72, identifier:rot_crop_matrix; 73, identifier:shape; 74, attribute; 75, argument_list; 76, assignment; 77, assignment; 78, assignment; 79, identifier:i; 80, call; 81, block; 82, unary_operator; 83, identifier:fmin; 84, argument_list; 85, attribute; 86, argument_list; 87, identifier:_fill_matrix; 88, argument_list; 89, identifier:n_clusters; 90, identifier:rot_matrix; 91, slice; 92, integer:1; 93, identifier:np; 94, identifier:reshape; 95, identifier:rot_crop_matrix; 96, binary_operator:x * y; 97, identifier:rot_crop_matrix; 98, call; 99, identifier:rot_matrix; 100, call; 101, identifier:result; 102, integer:0; 103, identifier:range; 104, argument_list; 105, for_statement; 106, identifier:result; 107, identifier:susanna_func; 108, identifier:rot_crop_vec; 109, keyword_argument; 110, keyword_argument; 111, identifier:np; 112, identifier:reshape; 113, identifier:rot_crop_vec_opt; 114, tuple; 115, identifier:rot_crop_matrix; 116, identifier:eigvectors; 117, integer:1; 118, identifier:x; 119, identifier:y; 120, attribute; 121, argument_list; 122, identifier:_fill_matrix; 123, argument_list; 124, integer:0; 125, identifier:n_clusters; 126, identifier:j; 127, call; 128, block; 129, identifier:args; 130, tuple; 131, identifier:disp; 132, False; 133, identifier:x; 134, identifier:y; 135, identifier:np; 136, identifier:reshape; 137, identifier:rot_crop_vec; 138, tuple; 139, identifier:rot_crop_matrix; 140, identifier:eigvectors; 141, identifier:range; 142, argument_list; 143, expression_statement; 144, identifier:eigvectors; 145, identifier:x; 146, identifier:y; 147, integer:0; 148, identifier:n_clusters; 149, augmented_assignment; 150, identifier:result; 151, binary_operator:np.power(rot_matrix[j, i], 2) / rot_matrix[0, i]; 152, call; 153, subscript; 154, attribute; 155, argument_list; 156, identifier:rot_matrix; 157, integer:0; 158, identifier:i; 159, identifier:np; 160, identifier:power; 161, subscript; 162, integer:2; 163, identifier:rot_matrix; 164, identifier:j; 165, identifier:i | 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; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 8, 24; 10, 25; 13, 26; 14, 27; 16, 28; 18, 29; 18, 30; 18, 31; 18, 32; 19, 33; 19, 34; 20, 35; 21, 36; 22, 37; 23, 38; 25, 39; 25, 40; 26, 41; 26, 42; 27, 43; 27, 44; 28, 45; 28, 46; 30, 47; 30, 48; 32, 49; 32, 50; 32, 51; 32, 52; 32, 53; 32, 54; 33, 55; 33, 56; 34, 57; 35, 58; 35, 59; 36, 60; 36, 61; 37, 62; 37, 63; 40, 64; 40, 65; 40, 66; 42, 67; 42, 68; 42, 69; 43, 70; 43, 71; 44, 72; 44, 73; 46, 74; 46, 75; 49, 76; 51, 77; 52, 78; 53, 79; 53, 80; 53, 81; 54, 82; 59, 83; 59, 84; 61, 85; 61, 86; 63, 87; 63, 88; 66, 89; 67, 90; 67, 91; 69, 92; 74, 93; 74, 94; 75, 95; 75, 96; 76, 97; 76, 98; 77, 99; 77, 100; 78, 101; 78, 102; 80, 103; 80, 104; 81, 105; 82, 106; 84, 107; 84, 108; 84, 109; 84, 110; 85, 111; 85, 112; 86, 113; 86, 114; 88, 115; 88, 116; 91, 117; 96, 118; 96, 119; 98, 120; 98, 121; 100, 122; 100, 123; 104, 124; 104, 125; 105, 126; 105, 127; 105, 128; 109, 129; 109, 130; 110, 131; 110, 132; 114, 133; 114, 134; 120, 135; 120, 136; 121, 137; 121, 138; 123, 139; 123, 140; 127, 141; 127, 142; 128, 143; 130, 144; 138, 145; 138, 146; 142, 147; 142, 148; 143, 149; 149, 150; 149, 151; 151, 152; 151, 153; 152, 154; 152, 155; 153, 156; 153, 157; 153, 158; 154, 159; 154, 160; 155, 161; 155, 162; 161, 163; 161, 164; 161, 165 | def _opt_soft(eigvectors, rot_matrix, n_clusters):
"""
Optimizes the PCCA+ rotation matrix such that the memberships are exclusively nonnegative.
Parameters
----------
eigenvectors : ndarray
A matrix with the sorted eigenvectors in the columns. The stationary eigenvector should
be first, then the one to the slowest relaxation process, etc.
rot_mat : ndarray (m x m)
nonoptimized rotation matrix
n_clusters : int
Number of clusters to group to.
Returns
-------
rot_mat : ndarray (m x m)
Optimized rotation matrix that rotates the dominant eigenvectors to yield the PCCA memberships, i.e.:
chi = np.dot(evec, rot_matrix
References
----------
[1] S. Roeblitz and M. Weber, Fuzzy spectral clustering by PCCA+:
application to Markov state models and data classification.
Adv Data Anal Classif 7, 147-179 (2013).
"""
# only consider first n_clusters eigenvectors
eigvectors = eigvectors[:, :n_clusters]
# crop first row and first column from rot_matrix
# rot_crop_matrix = rot_matrix[1:,1:]
rot_crop_matrix = rot_matrix[1:][:, 1:]
(x, y) = rot_crop_matrix.shape
# reshape rot_crop_matrix into linear vector
rot_crop_vec = np.reshape(rot_crop_matrix, x * y)
# Susanna Roeblitz' target function for optimization
def susanna_func(rot_crop_vec, eigvectors):
# reshape into matrix
rot_crop_matrix = np.reshape(rot_crop_vec, (x, y))
# fill matrix
rot_matrix = _fill_matrix(rot_crop_matrix, eigvectors)
result = 0
for i in range(0, n_clusters):
for j in range(0, n_clusters):
result += np.power(rot_matrix[j, i], 2) / rot_matrix[0, i]
return -result
from scipy.optimize import fmin
rot_crop_vec_opt = fmin(susanna_func, rot_crop_vec, args=(eigvectors,), disp=False)
rot_crop_matrix = np.reshape(rot_crop_vec_opt, (x, y))
rot_matrix = _fill_matrix(rot_crop_matrix, eigvectors)
return rot_matrix |
0, module; 1, function_definition; 2, function_name:connected_sets; 3, parameters; 4, block; 5, identifier:C; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, identifier:directed; 10, True; 11, comment:r"""Compute connected sets of microstates.
Connected components for a directed graph with edge-weights
given by the count matrix.
Parameters
----------
C : scipy.sparse matrix
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components for a directed or
undirected graph. Default is True.
Returns
-------
cc : list of arrays of integers
Each entry is an array containing all vertices (states) in the
corresponding connected component. The list is sorted
according to the size of the individual components. The
largest connected set is the first entry in the list, lcc=cc[0].
Notes
-----
Viewing the count matrix as the adjacency matrix of a (directed) graph
the connected components are given by the connected components of that
graph. Connected components of a graph can be efficiently computed
using Tarjan's algorithm.
References
----------
.. [1] Tarjan, R E. 1972. Depth-first search and linear graph
algorithms. SIAM Journal on Computing 1 (2): 146-160.
Examples
--------
>>> import numpy as np
>>> from msmtools.estimation import connected_sets
>>> C = np.array([[10, 1, 0], [2, 0, 3], [0, 0, 4]])
>>> cc_directed = connected_sets(C)
>>> cc_directed
[array([0, 1]), array([2])]
>>> cc_undirected = connected_sets(C, directed=False)
>>> cc_undirected
[array([0, 1, 2])]
"""; 12, call; 13, block; 14, else_clause; 15, identifier:isdense; 16, argument_list; 17, return_statement; 18, block; 19, identifier:C; 20, call; 21, return_statement; 22, attribute; 23, argument_list; 24, call; 25, attribute; 26, identifier:connected_sets; 27, call; 28, keyword_argument; 29, attribute; 30, argument_list; 31, identifier:sparse; 32, identifier:connectivity; 33, identifier:csr_matrix; 34, argument_list; 35, identifier:directed; 36, identifier:directed; 37, attribute; 38, identifier:connected_sets; 39, identifier:C; 40, keyword_argument; 41, identifier:C; 42, identifier:sparse; 43, identifier:connectivity; 44, identifier:directed; 45, identifier:directed | 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; 12, 15; 12, 16; 13, 17; 14, 18; 16, 19; 17, 20; 18, 21; 20, 22; 20, 23; 21, 24; 22, 25; 22, 26; 23, 27; 23, 28; 24, 29; 24, 30; 25, 31; 25, 32; 27, 33; 27, 34; 28, 35; 28, 36; 29, 37; 29, 38; 30, 39; 30, 40; 34, 41; 37, 42; 37, 43; 40, 44; 40, 45 | def connected_sets(C, directed=True):
r"""Compute connected sets of microstates.
Connected components for a directed graph with edge-weights
given by the count matrix.
Parameters
----------
C : scipy.sparse matrix
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components for a directed or
undirected graph. Default is True.
Returns
-------
cc : list of arrays of integers
Each entry is an array containing all vertices (states) in the
corresponding connected component. The list is sorted
according to the size of the individual components. The
largest connected set is the first entry in the list, lcc=cc[0].
Notes
-----
Viewing the count matrix as the adjacency matrix of a (directed) graph
the connected components are given by the connected components of that
graph. Connected components of a graph can be efficiently computed
using Tarjan's algorithm.
References
----------
.. [1] Tarjan, R E. 1972. Depth-first search and linear graph
algorithms. SIAM Journal on Computing 1 (2): 146-160.
Examples
--------
>>> import numpy as np
>>> from msmtools.estimation import connected_sets
>>> C = np.array([[10, 1, 0], [2, 0, 3], [0, 0, 4]])
>>> cc_directed = connected_sets(C)
>>> cc_directed
[array([0, 1]), array([2])]
>>> cc_undirected = connected_sets(C, directed=False)
>>> cc_undirected
[array([0, 1, 2])]
"""
if isdense(C):
return sparse.connectivity.connected_sets(csr_matrix(C), directed=directed)
else:
return sparse.connectivity.connected_sets(C, directed=directed) |
0, module; 1, function_definition; 2, function_name:zcount; 3, parameters; 4, block; 5, identifier:self; 6, identifier:name; 7, identifier:score_start; 8, identifier:score_end; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, comment:"""
Returns the number of elements in the sorted set at key ``name`` with
a score between ``score_start`` and ``score_end``.
Like **Redis.ZCOUNT**
.. note:: The range is [``score_start``, ``score_end``]
:param string name: the zset name
:param int score_start: The minimum score related to keys(included),
empty string ``''`` means -inf
:param int score_end: The maximum score(included) related to keys,
empty string ``''`` means +inf
:return: the number of keys in specified range
:rtype: int
>>> ssdb.zount('zset_1', 20, 70)
3
>>> ssdb.zcount('zset_1', 0, 100)
6
>>> ssdb.zcount('zset_1', 2, 3)
0
"""; 14, assignment; 15, assignment; 16, call; 17, identifier:score_start; 18, call; 19, identifier:score_end; 20, call; 21, attribute; 22, argument_list; 23, identifier:get_integer_or_emptystring; 24, argument_list; 25, identifier:get_integer_or_emptystring; 26, argument_list; 27, identifier:self; 28, identifier:execute_command; 29, string; 30, identifier:name; 31, identifier:score_start; 32, identifier:score_end; 33, string; 34, identifier:score_start; 35, string; 36, identifier:score_end; 37, string_content:zcount; 38, string_content:score_start; 39, string_content:score_end | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 9, 13; 10, 14; 11, 15; 12, 16; 14, 17; 14, 18; 15, 19; 15, 20; 16, 21; 16, 22; 18, 23; 18, 24; 20, 25; 20, 26; 21, 27; 21, 28; 22, 29; 22, 30; 22, 31; 22, 32; 24, 33; 24, 34; 26, 35; 26, 36; 29, 37; 33, 38; 35, 39 | def zcount(self, name, score_start, score_end):
"""
Returns the number of elements in the sorted set at key ``name`` with
a score between ``score_start`` and ``score_end``.
Like **Redis.ZCOUNT**
.. note:: The range is [``score_start``, ``score_end``]
:param string name: the zset name
:param int score_start: The minimum score related to keys(included),
empty string ``''`` means -inf
:param int score_end: The maximum score(included) related to keys,
empty string ``''`` means +inf
:return: the number of keys in specified range
:rtype: int
>>> ssdb.zount('zset_1', 20, 70)
3
>>> ssdb.zcount('zset_1', 0, 100)
6
>>> ssdb.zcount('zset_1', 2, 3)
0
"""
score_start = get_integer_or_emptystring('score_start', score_start)
score_end = get_integer_or_emptystring('score_end', score_end)
return self.execute_command('zcount', name, score_start, score_end) |
0, module; 1, function_definition; 2, function_name:reload_index; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, while_statement; 11, expression_statement; 12, expression_statement; 13, identifier:progress_cb; 14, identifier:dummy_progress_cb; 15, comment:"""
Read the index, and load the document list from it
Arguments:
callback --- called during the indexation (may be called *often*).
step : DocSearch.INDEX_STEP_READING or
DocSearch.INDEX_STEP_SORTING
progression : how many elements done yet
total : number of elements to do
document (only if step == DocSearch.INDEX_STEP_READING): file
being read
"""; 16, assignment; 17, assignment; 18, call; 19, block; 20, call; 21, call; 22, identifier:nb_results; 23, call; 24, identifier:progress; 25, integer:0; 26, attribute; 27, argument_list; 28, expression_statement; 29, expression_statement; 30, identifier:progress_cb; 31, argument_list; 32, attribute; 33, argument_list; 34, attribute; 35, argument_list; 36, attribute; 37, identifier:continue_reload_index; 38, call; 39, augmented_assignment; 40, integer:1; 41, integer:1; 42, attribute; 43, attribute; 44, identifier:end_reload_index; 45, attribute; 46, identifier:start_reload_index; 47, identifier:self; 48, identifier:index; 49, identifier:progress_cb; 50, argument_list; 51, identifier:progress; 52, integer:1; 53, identifier:self; 54, identifier:INDEX_STEP_LOADING; 55, identifier:self; 56, identifier:index; 57, identifier:self; 58, identifier:index; 59, identifier:progress; 60, identifier:nb_results; 61, attribute; 62, identifier:self; 63, identifier:INDEX_STEP_LOADING | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 6, 13; 6, 14; 7, 15; 8, 16; 9, 17; 10, 18; 10, 19; 11, 20; 12, 21; 16, 22; 16, 23; 17, 24; 17, 25; 18, 26; 18, 27; 19, 28; 19, 29; 20, 30; 20, 31; 21, 32; 21, 33; 23, 34; 23, 35; 26, 36; 26, 37; 28, 38; 29, 39; 31, 40; 31, 41; 31, 42; 32, 43; 32, 44; 34, 45; 34, 46; 36, 47; 36, 48; 38, 49; 38, 50; 39, 51; 39, 52; 42, 53; 42, 54; 43, 55; 43, 56; 45, 57; 45, 58; 50, 59; 50, 60; 50, 61; 61, 62; 61, 63 | def reload_index(self, progress_cb=dummy_progress_cb):
"""
Read the index, and load the document list from it
Arguments:
callback --- called during the indexation (may be called *often*).
step : DocSearch.INDEX_STEP_READING or
DocSearch.INDEX_STEP_SORTING
progression : how many elements done yet
total : number of elements to do
document (only if step == DocSearch.INDEX_STEP_READING): file
being read
"""
nb_results = self.index.start_reload_index()
progress = 0
while self.index.continue_reload_index():
progress_cb(progress, nb_results, self.INDEX_STEP_LOADING)
progress += 1
progress_cb(1, 1, self.INDEX_STEP_LOADING)
self.index.end_reload_index() |
0, module; 1, function_definition; 2, function_name:__doc_cmp; 3, parameters; 4, block; 5, identifier:self; 6, identifier:other; 7, expression_statement; 8, if_statement; 9, if_statement; 10, if_statement; 11, comment:"""
Comparison function. Can be used to sort docs alphabetically.
"""; 12, comparison_operator:other is None; 13, block; 14, boolean_operator; 15, block; 16, comparison_operator:self.__docid < other.__docid; 17, block; 18, elif_clause; 19, else_clause; 20, identifier:other; 21, None; 22, return_statement; 23, attribute; 24, attribute; 25, return_statement; 26, attribute; 27, attribute; 28, return_statement; 29, comparison_operator:self.__docid == other.__docid; 30, block; 31, block; 32, unary_operator; 33, identifier:self; 34, identifier:is_new; 35, identifier:other; 36, identifier:is_new; 37, integer:0; 38, identifier:self; 39, identifier:__docid; 40, identifier:other; 41, identifier:__docid; 42, unary_operator; 43, attribute; 44, attribute; 45, return_statement; 46, return_statement; 47, integer:1; 48, integer:1; 49, identifier:self; 50, identifier:__docid; 51, identifier:other; 52, identifier:__docid; 53, integer:0; 54, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 8, 13; 9, 14; 9, 15; 10, 16; 10, 17; 10, 18; 10, 19; 12, 20; 12, 21; 13, 22; 14, 23; 14, 24; 15, 25; 16, 26; 16, 27; 17, 28; 18, 29; 18, 30; 19, 31; 22, 32; 23, 33; 23, 34; 24, 35; 24, 36; 25, 37; 26, 38; 26, 39; 27, 40; 27, 41; 28, 42; 29, 43; 29, 44; 30, 45; 31, 46; 32, 47; 42, 48; 43, 49; 43, 50; 44, 51; 44, 52; 45, 53; 46, 54 | def __doc_cmp(self, other):
"""
Comparison function. Can be used to sort docs alphabetically.
"""
if other is None:
return -1
if self.is_new and other.is_new:
return 0
if self.__docid < other.__docid:
return -1
elif self.__docid == other.__docid:
return 0
else:
return 1 |
0, module; 1, function_definition; 2, function_name:__label_cmp; 3, parameters; 4, block; 5, identifier:self; 6, identifier:other; 7, expression_statement; 8, if_statement; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, if_statement; 13, comment:"""
Comparaison function. Can be used to sort labels alphabetically.
"""; 14, comparison_operator:other is None; 15, block; 16, assignment; 17, assignment; 18, comparison_operator:label_name < other_name; 19, block; 20, elif_clause; 21, else_clause; 22, comparison_operator:self.get_color_str() < other.get_color_str(); 23, block; 24, elif_clause; 25, else_clause; 26, identifier:other; 27, None; 28, return_statement; 29, identifier:label_name; 30, call; 31, identifier:other_name; 32, call; 33, identifier:label_name; 34, identifier:other_name; 35, return_statement; 36, comparison_operator:label_name == other_name; 37, block; 38, block; 39, call; 40, call; 41, return_statement; 42, comparison_operator:self.get_color_str() == other.get_color_str(); 43, block; 44, block; 45, unary_operator; 46, attribute; 47, argument_list; 48, attribute; 49, argument_list; 50, unary_operator; 51, identifier:label_name; 52, identifier:other_name; 53, return_statement; 54, return_statement; 55, attribute; 56, argument_list; 57, attribute; 58, argument_list; 59, unary_operator; 60, call; 61, call; 62, return_statement; 63, return_statement; 64, integer:1; 65, call; 66, identifier:lower; 67, call; 68, identifier:lower; 69, integer:1; 70, integer:0; 71, integer:1; 72, identifier:self; 73, identifier:get_color_str; 74, identifier:other; 75, identifier:get_color_str; 76, integer:1; 77, attribute; 78, argument_list; 79, attribute; 80, argument_list; 81, integer:0; 82, integer:1; 83, identifier:strip_accents; 84, argument_list; 85, identifier:strip_accents; 86, argument_list; 87, identifier:self; 88, identifier:get_color_str; 89, identifier:other; 90, identifier:get_color_str; 91, attribute; 92, attribute; 93, identifier:self; 94, identifier:name; 95, identifier:other; 96, identifier: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; 8, 15; 9, 16; 10, 17; 11, 18; 11, 19; 11, 20; 11, 21; 12, 22; 12, 23; 12, 24; 12, 25; 14, 26; 14, 27; 15, 28; 16, 29; 16, 30; 17, 31; 17, 32; 18, 33; 18, 34; 19, 35; 20, 36; 20, 37; 21, 38; 22, 39; 22, 40; 23, 41; 24, 42; 24, 43; 25, 44; 28, 45; 30, 46; 30, 47; 32, 48; 32, 49; 35, 50; 36, 51; 36, 52; 37, 53; 38, 54; 39, 55; 39, 56; 40, 57; 40, 58; 41, 59; 42, 60; 42, 61; 43, 62; 44, 63; 45, 64; 46, 65; 46, 66; 48, 67; 48, 68; 50, 69; 53, 70; 54, 71; 55, 72; 55, 73; 57, 74; 57, 75; 59, 76; 60, 77; 60, 78; 61, 79; 61, 80; 62, 81; 63, 82; 65, 83; 65, 84; 67, 85; 67, 86; 77, 87; 77, 88; 79, 89; 79, 90; 84, 91; 86, 92; 91, 93; 91, 94; 92, 95; 92, 96 | def __label_cmp(self, other):
"""
Comparaison function. Can be used to sort labels alphabetically.
"""
if other is None:
return -1
label_name = strip_accents(self.name).lower()
other_name = strip_accents(other.name).lower()
if label_name < other_name:
return -1
elif label_name == other_name:
return 0
else:
return 1
if self.get_color_str() < other.get_color_str():
return -1
elif self.get_color_str() == other.get_color_str():
return 0
else:
return 1 |
0, module; 1, function_definition; 2, function_name:stop_sequence; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, return_statement; 8, comment:"""Return the sorted StopTimes for this trip."""; 9, call; 10, identifier:sorted; 11, argument_list; 12, call; 13, keyword_argument; 14, attribute; 15, argument_list; 16, identifier:key; 17, lambda; 18, identifier:self; 19, identifier:stop_times; 20, lambda_parameters; 21, call; 22, identifier:x; 23, identifier:int; 24, argument_list; 25, call; 26, attribute; 27, argument_list; 28, identifier:x; 29, identifier:get; 30, string; 31, string_content:stop_sequence | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 9, 10; 9, 11; 11, 12; 11, 13; 12, 14; 12, 15; 13, 16; 13, 17; 14, 18; 14, 19; 17, 20; 17, 21; 20, 22; 21, 23; 21, 24; 24, 25; 25, 26; 25, 27; 26, 28; 26, 29; 27, 30; 30, 31 | def stop_sequence(self):
"""Return the sorted StopTimes for this trip."""
return sorted(
self.stop_times(),
key=lambda x:int(x.get('stop_sequence'))
) |
0, module; 1, function_definition; 2, function_name:near; 3, parameters; 4, block; 5, identifier:cls; 6, identifier:collection; 7, identifier:latitude; 8, identifier:longitude; 9, identifier:index_id; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, expression_statement; 14, expression_statement; 15, return_statement; 16, identifier:distance; 17, None; 18, identifier:skip; 19, None; 20, identifier:limit; 21, None; 22, comment:"""
The default will find at most 100 documents near the given coordinate.
The returned list is sorted according to the distance, with the nearest document being first in the list.
If there are near documents of equal distance, documents are chosen randomly from this set until
the limit is reached.
In order to use the near operator, a geo index must be defined for the collection.
This index also defines which attribute holds the coordinates for the document.
If you have more then one geo-spatial index, you can use the geo field to select a particular index.
:param collection Collection instance
:param latitude The latitude of the coordinate
:param longitude The longitude of the coordinate
:param index_id ID of the index which should be used for the query
:param distance If given, the attribute key used to return the distance to the given coordinate.
If specified, distances are returned in meters.
:param skip The number of documents to skip in the query
:param limit The maximal amount of documents to return. The skip is applied before the limit restriction.
:returns Document list
"""; 23, assignment; 24, call; 25, identifier:kwargs; 26, dictionary; 27, attribute; 28, argument_list; 29, pair; 30, pair; 31, pair; 32, pair; 33, pair; 34, pair; 35, identifier:cls; 36, identifier:_construct_query; 37, keyword_argument; 38, keyword_argument; 39, keyword_argument; 40, dictionary_splat; 41, string; 42, identifier:index_id; 43, string; 44, identifier:latitude; 45, string; 46, identifier:longitude; 47, string; 48, identifier:distance; 49, string; 50, identifier:skip; 51, string; 52, identifier:limit; 53, identifier:name; 54, string; 55, identifier:collection; 56, identifier:collection; 57, identifier:multiple; 58, True; 59, identifier:kwargs; 60, string_content:geo; 61, string_content:latitude; 62, string_content:longitude; 63, string_content:distance; 64, string_content:skip; 65, string_content:limit; 66, string_content:near | 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; 10, 16; 10, 17; 11, 18; 11, 19; 12, 20; 12, 21; 13, 22; 14, 23; 15, 24; 23, 25; 23, 26; 24, 27; 24, 28; 26, 29; 26, 30; 26, 31; 26, 32; 26, 33; 26, 34; 27, 35; 27, 36; 28, 37; 28, 38; 28, 39; 28, 40; 29, 41; 29, 42; 30, 43; 30, 44; 31, 45; 31, 46; 32, 47; 32, 48; 33, 49; 33, 50; 34, 51; 34, 52; 37, 53; 37, 54; 38, 55; 38, 56; 39, 57; 39, 58; 40, 59; 41, 60; 43, 61; 45, 62; 47, 63; 49, 64; 51, 65; 54, 66 | def near(cls, collection, latitude, longitude, index_id, distance=None, skip=None, limit=None):
"""
The default will find at most 100 documents near the given coordinate.
The returned list is sorted according to the distance, with the nearest document being first in the list.
If there are near documents of equal distance, documents are chosen randomly from this set until
the limit is reached.
In order to use the near operator, a geo index must be defined for the collection.
This index also defines which attribute holds the coordinates for the document.
If you have more then one geo-spatial index, you can use the geo field to select a particular index.
:param collection Collection instance
:param latitude The latitude of the coordinate
:param longitude The longitude of the coordinate
:param index_id ID of the index which should be used for the query
:param distance If given, the attribute key used to return the distance to the given coordinate.
If specified, distances are returned in meters.
:param skip The number of documents to skip in the query
:param limit The maximal amount of documents to return. The skip is applied before the limit restriction.
:returns Document list
"""
kwargs = {
'geo': index_id,
'latitude': latitude,
'longitude': longitude,
'distance': distance,
'skip': skip,
'limit': limit,
}
return cls._construct_query(name='near',
collection=collection, multiple=True,
**kwargs) |
0, module; 1, function_definition; 2, function_name:rank_targets; 3, parameters; 4, block; 5, identifier:sample_frame; 6, identifier:ref_targets; 7, identifier:ref_sample; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, while_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, return_statement; 22, comment:"""Uses the geNorm algorithm to determine the most stably expressed
genes from amongst ref_targets in your sample.
See Vandesompele et al.'s 2002 Genome Biology paper for information about
the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-research0034
:param DataFrame sample_frame: A sample data frame.
:param iterable ref_targets: A sequence of targets from the Target column
of sample_frame to consider for ranking.
:param string ref_sample: The name of a sample from the Sample
column of sample_frame. It doesn't really matter what it is but it
should exist for every target.
:return: a sorted DataFrame with two columns, 'Target' and 'M' (the
relative stability; lower means more stable).
:rtype: DataFrame
"""; 23, assignment; 24, assignment; 25, assignment; 26, assignment; 27, assignment; 28, assignment; 29, assignment; 30, comparison_operator:len(ref_targets) - len(worst) > 1; 31, block; 32, assignment; 33, call; 34, call; 35, assignment; 36, call; 37, identifier:table; 38, call; 39, identifier:all_samples; 40, call; 41, identifier:t; 42, call; 43, identifier:logt; 44, call; 45, identifier:ref_targets; 46, call; 47, identifier:worst; 48, list; 49, identifier:worst_m; 50, list; 51, binary_operator:len(ref_targets) - len(worst); 52, integer:1; 53, expression_statement; 54, for_statement; 55, expression_statement; 56, expression_statement; 57, identifier:best; 58, binary_operator:ref_targets - set(worst); 59, attribute; 60, argument_list; 61, attribute; 62, argument_list; 63, identifier:worst_m; 64, binary_operator:[worst_m[0]] + worst_m; 65, attribute; 66, argument_list; 67, identifier:collect_expression; 68, argument_list; 69, attribute; 70, argument_list; 71, attribute; 72, argument_list; 73, identifier:log2; 74, argument_list; 75, identifier:set; 76, argument_list; 77, call; 78, call; 79, assignment; 80, identifier:test_target; 81, identifier:ref_targets; 82, block; 83, call; 84, call; 85, identifier:ref_targets; 86, call; 87, identifier:worst; 88, identifier:reverse; 89, identifier:worst_m; 90, identifier:reverse; 91, list; 92, identifier:worst_m; 93, identifier:pd; 94, identifier:DataFrame; 95, dictionary; 96, keyword_argument; 97, identifier:sample_frame; 98, identifier:ref_targets; 99, identifier:ref_sample; 100, subscript; 101, identifier:unique; 102, call; 103, identifier:mean; 104, identifier:t; 105, identifier:ref_targets; 106, identifier:len; 107, argument_list; 108, identifier:len; 109, argument_list; 110, identifier:M; 111, list; 112, if_statement; 113, expression_statement; 114, for_statement; 115, expression_statement; 116, attribute; 117, argument_list; 118, attribute; 119, argument_list; 120, identifier:set; 121, argument_list; 122, subscript; 123, pair; 124, pair; 125, identifier:columns; 126, list; 127, identifier:sample_frame; 128, string; 129, attribute; 130, argument_list; 131, identifier:ref_targets; 132, identifier:worst; 133, comparison_operator:test_target in worst; 134, block; 135, assignment; 136, identifier:ref_target; 137, identifier:ref_targets; 138, block; 139, call; 140, identifier:worst; 141, identifier:append; 142, subscript; 143, identifier:worst_m; 144, identifier:append; 145, subscript; 146, identifier:worst; 147, identifier:worst_m; 148, integer:0; 149, string; 150, binary_operator:list(best) + worst; 151, string; 152, identifier:worst_m; 153, string; 154, string; 155, string_content:Sample; 156, identifier:table; 157, identifier:groupby; 158, list; 159, identifier:test_target; 160, identifier:worst; 161, continue_statement; 162, identifier:Vs; 163, list; 164, if_statement; 165, expression_statement; 166, expression_statement; 167, attribute; 168, argument_list; 169, call; 170, integer:1; 171, call; 172, integer:0; 173, string_content:Target; 174, call; 175, identifier:worst; 176, string_content:M; 177, string_content:Target; 178, string_content:M; 179, string; 180, string; 181, boolean_operator; 182, block; 183, assignment; 184, call; 185, identifier:M; 186, identifier:append; 187, tuple; 188, identifier:max; 189, argument_list; 190, identifier:max; 191, argument_list; 192, identifier:list; 193, argument_list; 194, string_content:Sample; 195, string_content:Target; 196, comparison_operator:ref_target == test_target; 197, comparison_operator:ref_target in worst; 198, continue_statement; 199, identifier:A; 200, subscript; 201, attribute; 202, argument_list; 203, binary_operator:sum(Vs)/(len(ref_targets)-len(worst)-1); 204, identifier:test_target; 205, identifier:M; 206, identifier:M; 207, identifier:best; 208, identifier:ref_target; 209, identifier:test_target; 210, identifier:ref_target; 211, identifier:worst; 212, attribute; 213, call; 214, identifier:ref_target; 215, identifier:Vs; 216, identifier:append; 217, call; 218, call; 219, parenthesized_expression; 220, identifier:logt; 221, identifier:ix; 222, identifier:zip; 223, argument_list; 224, attribute; 225, argument_list; 226, identifier:sum; 227, argument_list; 228, binary_operator:len(ref_targets)-len(worst)-1; 229, identifier:all_samples; 230, call; 231, identifier:A; 232, identifier:std; 233, identifier:Vs; 234, binary_operator:len(ref_targets)-len(worst); 235, integer:1; 236, identifier:repeat; 237, argument_list; 238, call; 239, call; 240, identifier:test_target; 241, identifier:len; 242, argument_list; 243, identifier:len; 244, argument_list; 245, identifier:ref_targets; 246, identifier:worst | 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; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 8, 22; 9, 23; 10, 24; 11, 25; 12, 26; 13, 27; 14, 28; 15, 29; 16, 30; 16, 31; 17, 32; 18, 33; 19, 34; 20, 35; 21, 36; 23, 37; 23, 38; 24, 39; 24, 40; 25, 41; 25, 42; 26, 43; 26, 44; 27, 45; 27, 46; 28, 47; 28, 48; 29, 49; 29, 50; 30, 51; 30, 52; 31, 53; 31, 54; 31, 55; 31, 56; 32, 57; 32, 58; 33, 59; 33, 60; 34, 61; 34, 62; 35, 63; 35, 64; 36, 65; 36, 66; 38, 67; 38, 68; 40, 69; 40, 70; 42, 71; 42, 72; 44, 73; 44, 74; 46, 75; 46, 76; 51, 77; 51, 78; 53, 79; 54, 80; 54, 81; 54, 82; 55, 83; 56, 84; 58, 85; 58, 86; 59, 87; 59, 88; 61, 89; 61, 90; 64, 91; 64, 92; 65, 93; 65, 94; 66, 95; 66, 96; 68, 97; 68, 98; 68, 99; 69, 100; 69, 101; 71, 102; 71, 103; 74, 104; 76, 105; 77, 106; 77, 107; 78, 108; 78, 109; 79, 110; 79, 111; 82, 112; 82, 113; 82, 114; 82, 115; 83, 116; 83, 117; 84, 118; 84, 119; 86, 120; 86, 121; 91, 122; 95, 123; 95, 124; 96, 125; 96, 126; 100, 127; 100, 128; 102, 129; 102, 130; 107, 131; 109, 132; 112, 133; 112, 134; 113, 135; 114, 136; 114, 137; 114, 138; 115, 139; 116, 140; 116, 141; 117, 142; 118, 143; 118, 144; 119, 145; 121, 146; 122, 147; 122, 148; 123, 149; 123, 150; 124, 151; 124, 152; 126, 153; 126, 154; 128, 155; 129, 156; 129, 157; 130, 158; 133, 159; 133, 160; 134, 161; 135, 162; 135, 163; 138, 164; 138, 165; 138, 166; 139, 167; 139, 168; 142, 169; 142, 170; 145, 171; 145, 172; 149, 173; 150, 174; 150, 175; 151, 176; 153, 177; 154, 178; 158, 179; 158, 180; 164, 181; 164, 182; 165, 183; 166, 184; 167, 185; 167, 186; 168, 187; 169, 188; 169, 189; 171, 190; 171, 191; 174, 192; 174, 193; 179, 194; 180, 195; 181, 196; 181, 197; 182, 198; 183, 199; 183, 200; 184, 201; 184, 202; 187, 203; 187, 204; 189, 205; 191, 206; 193, 207; 196, 208; 196, 209; 197, 210; 197, 211; 200, 212; 200, 213; 200, 214; 201, 215; 201, 216; 202, 217; 203, 218; 203, 219; 212, 220; 212, 221; 213, 222; 213, 223; 217, 224; 217, 225; 218, 226; 218, 227; 219, 228; 223, 229; 223, 230; 224, 231; 224, 232; 227, 233; 228, 234; 228, 235; 230, 236; 230, 237; 234, 238; 234, 239; 237, 240; 238, 241; 238, 242; 239, 243; 239, 244; 242, 245; 244, 246 | def rank_targets(sample_frame, ref_targets, ref_sample):
"""Uses the geNorm algorithm to determine the most stably expressed
genes from amongst ref_targets in your sample.
See Vandesompele et al.'s 2002 Genome Biology paper for information about
the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-research0034
:param DataFrame sample_frame: A sample data frame.
:param iterable ref_targets: A sequence of targets from the Target column
of sample_frame to consider for ranking.
:param string ref_sample: The name of a sample from the Sample
column of sample_frame. It doesn't really matter what it is but it
should exist for every target.
:return: a sorted DataFrame with two columns, 'Target' and 'M' (the
relative stability; lower means more stable).
:rtype: DataFrame
"""
table = collect_expression(sample_frame, ref_targets, ref_sample)
all_samples = sample_frame['Sample'].unique()
t = table.groupby(['Sample', 'Target']).mean()
logt = log2(t)
ref_targets = set(ref_targets)
worst = []
worst_m = []
while len(ref_targets) - len(worst) > 1:
M = []
for test_target in ref_targets:
if test_target in worst: continue
Vs = []
for ref_target in ref_targets:
if ref_target == test_target or ref_target in worst: continue
A = logt.ix[zip(all_samples, repeat(test_target)), ref_target]
Vs.append(A.std())
M.append( (sum(Vs)/(len(ref_targets)-len(worst)-1), test_target) )
worst.append(max(M)[1])
worst_m.append(max(M)[0])
best = ref_targets - set(worst)
worst.reverse()
worst_m.reverse()
worst_m = [worst_m[0]] + worst_m
return pd.DataFrame({'Target': list(best) + worst, 'M': worst_m}, columns=['Target', 'M']) |
0, module; 1, function_definition; 2, function_name:natural_sort_key; 3, parameters; 4, block; 5, identifier:s; 6, expression_statement; 7, return_statement; 8, comment:"""
returns a key that can be used in sort functions.
Example:
>>> items = ['A99', 'a1', 'a2', 'a10', 'a24', 'a12', 'a100']
The normal sort function will ignore the natural order of the
integers in the string:
>>> print sorted(items)
['A99', 'a1', 'a10', 'a100', 'a12', 'a2', 'a24']
When we use this function as a key to the sort function,
the natural order of the integer is considered.
>>> print sorted(items, key=natural_sort_key)
['A99', 'a1', 'a2', 'a10', 'a12', 'a24', 'a100']
"""; 9, list_comprehension; 10, conditional_expression:int(text) if text.isdigit() else text; 11, for_in_clause; 12, call; 13, call; 14, identifier:text; 15, identifier:text; 16, call; 17, identifier:int; 18, argument_list; 19, attribute; 20, argument_list; 21, attribute; 22, argument_list; 23, identifier:text; 24, identifier:text; 25, identifier:isdigit; 26, identifier:re; 27, identifier:split; 28, identifier:INTEGER_RE; 29, call; 30, identifier:str; 31, argument_list; 32, identifier:s | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 9, 10; 9, 11; 10, 12; 10, 13; 10, 14; 11, 15; 11, 16; 12, 17; 12, 18; 13, 19; 13, 20; 16, 21; 16, 22; 18, 23; 19, 24; 19, 25; 21, 26; 21, 27; 22, 28; 22, 29; 29, 30; 29, 31; 31, 32 | def natural_sort_key(s):
"""
returns a key that can be used in sort functions.
Example:
>>> items = ['A99', 'a1', 'a2', 'a10', 'a24', 'a12', 'a100']
The normal sort function will ignore the natural order of the
integers in the string:
>>> print sorted(items)
['A99', 'a1', 'a10', 'a100', 'a12', 'a2', 'a24']
When we use this function as a key to the sort function,
the natural order of the integer is considered.
>>> print sorted(items, key=natural_sort_key)
['A99', 'a1', 'a2', 'a10', 'a12', 'a24', 'a100']
"""
return [int(text) if text.isdigit() else text
for text in re.split(INTEGER_RE, str(s))] |
0, module; 1, function_definition; 2, function_name:relabel_nodes; 3, parameters; 4, block; 5, identifier:G; 6, identifier:mapping; 7, default_parameter; 8, expression_statement; 9, comment:# you can pass a function f(old_label)->new_label; 10, comment:# but we'll just make a dictionary here regardless; 11, if_statement; 12, if_statement; 13, identifier:copy; 14, True; 15, comment:"""Relabel the nodes of the graph G.
Parameters
----------
G : graph
A NetworkX graph
mapping : dictionary
A dictionary with the old labels as keys and new labels as values.
A partial mapping is allowed.
copy : bool (optional, default=True)
If True return a copy, or if False relabel the nodes in place.
Examples
--------
>>> G=nx.path_graph(3) # nodes 0-1-2
>>> mapping={0:'a',1:'b',2:'c'}
>>> H=nx.relabel_nodes(G,mapping)
>>> print(sorted(H.nodes()))
['a', 'b', 'c']
>>> G=nx.path_graph(26) # nodes 0..25
>>> mapping=dict(zip(G.nodes(),"abcdefghijklmnopqrstuvwxyz"))
>>> H=nx.relabel_nodes(G,mapping) # nodes a..z
>>> mapping=dict(zip(G.nodes(),range(1,27)))
>>> G1=nx.relabel_nodes(G,mapping) # nodes 1..26
Partial in-place mapping:
>>> G=nx.path_graph(3) # nodes 0-1-2
>>> mapping={0:'a',1:'b'} # 0->'a' and 1->'b'
>>> G=nx.relabel_nodes(G,mapping, copy=False)
print(G.nodes())
[2, 'b', 'a']
Mapping as function:
>>> G=nx.path_graph(3)
>>> def mapping(x):
... return x**2
>>> H=nx.relabel_nodes(G,mapping)
>>> print(H.nodes())
[0, 1, 4]
Notes
-----
Only the nodes specified in the mapping will be relabeled.
The keyword setting copy=False modifies the graph in place.
This is not always possible if the mapping is circular.
In that case use copy=True.
See Also
--------
convert_node_labels_to_integers
"""; 16, not_operator; 17, block; 18, else_clause; 19, identifier:copy; 20, block; 21, else_clause; 22, call; 23, expression_statement; 24, block; 25, return_statement; 26, block; 27, identifier:hasattr; 28, argument_list; 29, assignment; 30, expression_statement; 31, call; 32, return_statement; 33, identifier:mapping; 34, string:"__getitem__"; 35, identifier:m; 36, call; 37, assignment; 38, identifier:_relabel_copy; 39, argument_list; 40, call; 41, identifier:dict; 42, generator_expression; 43, identifier:m; 44, identifier:mapping; 45, identifier:G; 46, identifier:m; 47, identifier:_relabel_inplace; 48, argument_list; 49, tuple; 50, for_in_clause; 51, identifier:G; 52, identifier:m; 53, identifier:n; 54, call; 55, identifier:n; 56, identifier:G; 57, identifier:mapping; 58, argument_list; 59, identifier:n | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 7, 14; 8, 15; 11, 16; 11, 17; 11, 18; 12, 19; 12, 20; 12, 21; 16, 22; 17, 23; 18, 24; 20, 25; 21, 26; 22, 27; 22, 28; 23, 29; 24, 30; 25, 31; 26, 32; 28, 33; 28, 34; 29, 35; 29, 36; 30, 37; 31, 38; 31, 39; 32, 40; 36, 41; 36, 42; 37, 43; 37, 44; 39, 45; 39, 46; 40, 47; 40, 48; 42, 49; 42, 50; 48, 51; 48, 52; 49, 53; 49, 54; 50, 55; 50, 56; 54, 57; 54, 58; 58, 59 | def relabel_nodes(G, mapping, copy=True):
"""Relabel the nodes of the graph G.
Parameters
----------
G : graph
A NetworkX graph
mapping : dictionary
A dictionary with the old labels as keys and new labels as values.
A partial mapping is allowed.
copy : bool (optional, default=True)
If True return a copy, or if False relabel the nodes in place.
Examples
--------
>>> G=nx.path_graph(3) # nodes 0-1-2
>>> mapping={0:'a',1:'b',2:'c'}
>>> H=nx.relabel_nodes(G,mapping)
>>> print(sorted(H.nodes()))
['a', 'b', 'c']
>>> G=nx.path_graph(26) # nodes 0..25
>>> mapping=dict(zip(G.nodes(),"abcdefghijklmnopqrstuvwxyz"))
>>> H=nx.relabel_nodes(G,mapping) # nodes a..z
>>> mapping=dict(zip(G.nodes(),range(1,27)))
>>> G1=nx.relabel_nodes(G,mapping) # nodes 1..26
Partial in-place mapping:
>>> G=nx.path_graph(3) # nodes 0-1-2
>>> mapping={0:'a',1:'b'} # 0->'a' and 1->'b'
>>> G=nx.relabel_nodes(G,mapping, copy=False)
print(G.nodes())
[2, 'b', 'a']
Mapping as function:
>>> G=nx.path_graph(3)
>>> def mapping(x):
... return x**2
>>> H=nx.relabel_nodes(G,mapping)
>>> print(H.nodes())
[0, 1, 4]
Notes
-----
Only the nodes specified in the mapping will be relabeled.
The keyword setting copy=False modifies the graph in place.
This is not always possible if the mapping is circular.
In that case use copy=True.
See Also
--------
convert_node_labels_to_integers
"""
# you can pass a function f(old_label)->new_label
# but we'll just make a dictionary here regardless
if not hasattr(mapping, "__getitem__"):
m = dict((n, mapping(n)) for n in G)
else:
m = mapping
if copy:
return _relabel_copy(G, m)
else:
return _relabel_inplace(G, m) |
0, module; 1, function_definition; 2, function_name:convert_node_labels_to_integers; 3, parameters; 4, block; 5, identifier:G; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, expression_statement; 13, expression_statement; 14, comment:# create node attribute with the old label; 15, if_statement; 16, return_statement; 17, identifier:first_label; 18, integer:0; 19, identifier:ordering; 20, string:"default"; 21, identifier:label_attribute; 22, None; 23, comment:"""Return a copy of the graph G with the nodes relabeled with integers.
Parameters
----------
G : graph
A NetworkX graph
first_label : int, optional (default=0)
An integer specifying the offset in numbering nodes.
The n new integer labels are numbered first_label, ..., n-1+first_label.
ordering : string
"default" : inherit node ordering from G.nodes()
"sorted" : inherit node ordering from sorted(G.nodes())
"increasing degree" : nodes are sorted by increasing degree
"decreasing degree" : nodes are sorted by decreasing degree
label_attribute : string, optional (default=None)
Name of node attribute to store old label. If None no attribute
is created.
Notes
-----
Node and edge attribute data are copied to the new (relabeled) graph.
See Also
--------
relabel_nodes
"""; 24, assignment; 25, comparison_operator:ordering == "default"; 26, block; 27, elif_clause; 28, elif_clause; 29, elif_clause; 30, else_clause; 31, assignment; 32, assignment; 33, comparison_operator:label_attribute is not None; 34, block; 35, identifier:H; 36, identifier:N; 37, binary_operator:G.number_of_nodes() + first_label; 38, identifier:ordering; 39, string:"default"; 40, expression_statement; 41, comparison_operator:ordering == "sorted"; 42, block; 43, comparison_operator:ordering == "increasing degree"; 44, block; 45, comparison_operator:ordering == "decreasing degree"; 46, block; 47, block; 48, identifier:H; 49, call; 50, attribute; 51, binary_operator:"(" + G.name + ")_with_int_labels"; 52, identifier:label_attribute; 53, None; 54, expression_statement; 55, call; 56, identifier:first_label; 57, assignment; 58, identifier:ordering; 59, string:"sorted"; 60, expression_statement; 61, expression_statement; 62, expression_statement; 63, identifier:ordering; 64, string:"increasing degree"; 65, expression_statement; 66, expression_statement; 67, comment:# in-place sort from lowest to highest degree; 68, expression_statement; 69, identifier:ordering; 70, string:"decreasing degree"; 71, expression_statement; 72, expression_statement; 73, comment:# in-place sort from lowest to highest degree; 74, expression_statement; 75, expression_statement; 76, raise_statement; 77, identifier:relabel_nodes; 78, argument_list; 79, identifier:H; 80, identifier:name; 81, binary_operator:"(" + G.name; 82, string:")_with_int_labels"; 83, call; 84, attribute; 85, argument_list; 86, identifier:mapping; 87, call; 88, assignment; 89, call; 90, assignment; 91, assignment; 92, call; 93, assignment; 94, assignment; 95, call; 96, call; 97, assignment; 98, call; 99, identifier:G; 100, identifier:mapping; 101, string:"("; 102, attribute; 103, attribute; 104, argument_list; 105, identifier:G; 106, identifier:number_of_nodes; 107, identifier:dict; 108, argument_list; 109, identifier:nlist; 110, call; 111, attribute; 112, argument_list; 113, identifier:mapping; 114, call; 115, identifier:dv_pairs; 116, list_comprehension; 117, attribute; 118, argument_list; 119, identifier:mapping; 120, call; 121, identifier:dv_pairs; 122, list_comprehension; 123, attribute; 124, argument_list; 125, attribute; 126, argument_list; 127, identifier:mapping; 128, call; 129, attribute; 130, argument_list; 131, identifier:G; 132, identifier:name; 133, identifier:nx; 134, identifier:set_node_attributes; 135, identifier:H; 136, identifier:label_attribute; 137, call; 138, call; 139, attribute; 140, argument_list; 141, identifier:nlist; 142, identifier:sort; 143, identifier:dict; 144, argument_list; 145, tuple; 146, for_in_clause; 147, identifier:dv_pairs; 148, identifier:sort; 149, identifier:dict; 150, argument_list; 151, tuple; 152, for_in_clause; 153, identifier:dv_pairs; 154, identifier:sort; 155, identifier:dv_pairs; 156, identifier:reverse; 157, identifier:dict; 158, argument_list; 159, identifier:nx; 160, identifier:NetworkXError; 161, call; 162, identifier:dict; 163, generator_expression; 164, identifier:zip; 165, argument_list; 166, identifier:G; 167, identifier:nodes; 168, call; 169, identifier:d; 170, identifier:n; 171, tuple_pattern; 172, call; 173, call; 174, identifier:d; 175, identifier:n; 176, tuple_pattern; 177, call; 178, call; 179, attribute; 180, argument_list; 181, tuple; 182, for_in_clause; 183, call; 184, call; 185, identifier:zip; 186, argument_list; 187, identifier:n; 188, identifier:d; 189, attribute; 190, argument_list; 191, identifier:zip; 192, argument_list; 193, identifier:n; 194, identifier:d; 195, attribute; 196, argument_list; 197, identifier:zip; 198, argument_list; 199, string; 200, identifier:format; 201, identifier:ordering; 202, identifier:v; 203, identifier:k; 204, pattern_list; 205, call; 206, attribute; 207, argument_list; 208, identifier:range; 209, argument_list; 210, identifier:nlist; 211, call; 212, identifier:G; 213, identifier:degree_iter; 214, list_comprehension; 215, call; 216, identifier:G; 217, identifier:degree_iter; 218, list_comprehension; 219, call; 220, string_content:Unknown node ordering: {0}; 221, identifier:k; 222, identifier:v; 223, attribute; 224, argument_list; 225, identifier:G; 226, identifier:nodes; 227, identifier:first_label; 228, identifier:N; 229, identifier:range; 230, argument_list; 231, identifier:n; 232, for_in_clause; 233, identifier:range; 234, argument_list; 235, identifier:n; 236, for_in_clause; 237, identifier:range; 238, argument_list; 239, identifier:mapping; 240, identifier:items; 241, identifier:first_label; 242, identifier:N; 243, pattern_list; 244, identifier:dv_pairs; 245, identifier:first_label; 246, identifier:N; 247, pattern_list; 248, identifier:dv_pairs; 249, identifier:first_label; 250, identifier:N; 251, identifier:d; 252, identifier:n; 253, identifier:d; 254, identifier:n | 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; 6, 17; 6, 18; 7, 19; 7, 20; 8, 21; 8, 22; 9, 23; 10, 24; 11, 25; 11, 26; 11, 27; 11, 28; 11, 29; 11, 30; 12, 31; 13, 32; 15, 33; 15, 34; 16, 35; 24, 36; 24, 37; 25, 38; 25, 39; 26, 40; 27, 41; 27, 42; 28, 43; 28, 44; 29, 45; 29, 46; 30, 47; 31, 48; 31, 49; 32, 50; 32, 51; 33, 52; 33, 53; 34, 54; 37, 55; 37, 56; 40, 57; 41, 58; 41, 59; 42, 60; 42, 61; 42, 62; 43, 63; 43, 64; 44, 65; 44, 66; 44, 67; 44, 68; 45, 69; 45, 70; 46, 71; 46, 72; 46, 73; 46, 74; 46, 75; 47, 76; 49, 77; 49, 78; 50, 79; 50, 80; 51, 81; 51, 82; 54, 83; 55, 84; 55, 85; 57, 86; 57, 87; 60, 88; 61, 89; 62, 90; 65, 91; 66, 92; 68, 93; 71, 94; 72, 95; 74, 96; 75, 97; 76, 98; 78, 99; 78, 100; 81, 101; 81, 102; 83, 103; 83, 104; 84, 105; 84, 106; 87, 107; 87, 108; 88, 109; 88, 110; 89, 111; 89, 112; 90, 113; 90, 114; 91, 115; 91, 116; 92, 117; 92, 118; 93, 119; 93, 120; 94, 121; 94, 122; 95, 123; 95, 124; 96, 125; 96, 126; 97, 127; 97, 128; 98, 129; 98, 130; 102, 131; 102, 132; 103, 133; 103, 134; 104, 135; 104, 136; 104, 137; 108, 138; 110, 139; 110, 140; 111, 141; 111, 142; 114, 143; 114, 144; 116, 145; 116, 146; 117, 147; 117, 148; 120, 149; 120, 150; 122, 151; 122, 152; 123, 153; 123, 154; 125, 155; 125, 156; 128, 157; 128, 158; 129, 159; 129, 160; 130, 161; 137, 162; 137, 163; 138, 164; 138, 165; 139, 166; 139, 167; 144, 168; 145, 169; 145, 170; 146, 171; 146, 172; 150, 173; 151, 174; 151, 175; 152, 176; 152, 177; 158, 178; 161, 179; 161, 180; 163, 181; 163, 182; 165, 183; 165, 184; 168, 185; 168, 186; 171, 187; 171, 188; 172, 189; 172, 190; 173, 191; 173, 192; 176, 193; 176, 194; 177, 195; 177, 196; 178, 197; 178, 198; 179, 199; 179, 200; 180, 201; 181, 202; 181, 203; 182, 204; 182, 205; 183, 206; 183, 207; 184, 208; 184, 209; 186, 210; 186, 211; 189, 212; 189, 213; 192, 214; 192, 215; 195, 216; 195, 217; 198, 218; 198, 219; 199, 220; 204, 221; 204, 222; 205, 223; 205, 224; 206, 225; 206, 226; 209, 227; 209, 228; 211, 229; 211, 230; 214, 231; 214, 232; 215, 233; 215, 234; 218, 235; 218, 236; 219, 237; 219, 238; 223, 239; 223, 240; 230, 241; 230, 242; 232, 243; 232, 244; 234, 245; 234, 246; 236, 247; 236, 248; 238, 249; 238, 250; 243, 251; 243, 252; 247, 253; 247, 254 | def convert_node_labels_to_integers(G, first_label=0, ordering="default",
label_attribute=None):
"""Return a copy of the graph G with the nodes relabeled with integers.
Parameters
----------
G : graph
A NetworkX graph
first_label : int, optional (default=0)
An integer specifying the offset in numbering nodes.
The n new integer labels are numbered first_label, ..., n-1+first_label.
ordering : string
"default" : inherit node ordering from G.nodes()
"sorted" : inherit node ordering from sorted(G.nodes())
"increasing degree" : nodes are sorted by increasing degree
"decreasing degree" : nodes are sorted by decreasing degree
label_attribute : string, optional (default=None)
Name of node attribute to store old label. If None no attribute
is created.
Notes
-----
Node and edge attribute data are copied to the new (relabeled) graph.
See Also
--------
relabel_nodes
"""
N = G.number_of_nodes() + first_label
if ordering == "default":
mapping = dict(zip(G.nodes(), range(first_label, N)))
elif ordering == "sorted":
nlist = G.nodes()
nlist.sort()
mapping = dict(zip(nlist, range(first_label, N)))
elif ordering == "increasing degree":
dv_pairs = [(d, n) for (n, d) in G.degree_iter()]
dv_pairs.sort() # in-place sort from lowest to highest degree
mapping = dict(zip([n for d, n in dv_pairs], range(first_label, N)))
elif ordering == "decreasing degree":
dv_pairs = [(d, n) for (n, d) in G.degree_iter()]
dv_pairs.sort() # in-place sort from lowest to highest degree
dv_pairs.reverse()
mapping = dict(zip([n for d, n in dv_pairs], range(first_label, N)))
else:
raise nx.NetworkXError('Unknown node ordering: {0}'.format(ordering))
H = relabel_nodes(G, mapping)
H.name = "(" + G.name + ")_with_int_labels"
# create node attribute with the old label
if label_attribute is not None:
nx.set_node_attributes(H, label_attribute,
dict((v, k) for k, v in mapping.items()))
return H |
0, module; 1, function_definition; 2, function_name:get_token_ids; 3, parameters; 4, block; 5, identifier:tree; 6, expression_statement; 7, function_definition; 8, expression_statement; 9, return_statement; 10, comment:"""
returns a list of all token IDs occuring the the given exmaralda file,
sorted by their time stamp in ascending order.
"""; 11, function_name:tok2time; 12, parameters; 13, block; 14, assignment; 15, generator_expression; 16, identifier:token_element; 17, expression_statement; 18, return_statement; 19, identifier:timeline; 20, call; 21, subscript; 22, for_in_clause; 23, string; 24, call; 25, attribute; 26, argument_list; 27, attribute; 28, string; 29, identifier:tok; 30, call; 31, string_content:extracts the time (float) of a <tli> element
(i.e. the absolute position of a token in the document); 32, identifier:float; 33, argument_list; 34, identifier:tree; 35, identifier:find; 36, string; 37, identifier:tok; 38, identifier:attrib; 39, string_content:id; 40, identifier:sorted; 41, argument_list; 42, subscript; 43, string_content://common-timeline; 44, generator_expression; 45, keyword_argument; 46, attribute; 47, string; 48, identifier:tli; 49, for_in_clause; 50, identifier:key; 51, identifier:tok2time; 52, identifier:token_element; 53, identifier:attrib; 54, string_content:time; 55, identifier:tli; 56, call; 57, attribute; 58, argument_list; 59, identifier:timeline; 60, identifier:iterchildren | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 7, 12; 7, 13; 8, 14; 9, 15; 12, 16; 13, 17; 13, 18; 14, 19; 14, 20; 15, 21; 15, 22; 17, 23; 18, 24; 20, 25; 20, 26; 21, 27; 21, 28; 22, 29; 22, 30; 23, 31; 24, 32; 24, 33; 25, 34; 25, 35; 26, 36; 27, 37; 27, 38; 28, 39; 30, 40; 30, 41; 33, 42; 36, 43; 41, 44; 41, 45; 42, 46; 42, 47; 44, 48; 44, 49; 45, 50; 45, 51; 46, 52; 46, 53; 47, 54; 49, 55; 49, 56; 56, 57; 56, 58; 57, 59; 57, 60 | def get_token_ids(tree):
"""
returns a list of all token IDs occuring the the given exmaralda file,
sorted by their time stamp in ascending order.
"""
def tok2time(token_element):
'''
extracts the time (float) of a <tli> element
(i.e. the absolute position of a token in the document)
'''
return float(token_element.attrib['time'])
timeline = tree.find('//common-timeline')
return (tok.attrib['id']
for tok in sorted((tli for tli in timeline.iterchildren()),
key=tok2time)) |
0, module; 1, function_definition; 2, function_name:get_span; 3, parameters; 4, block; 5, identifier:docgraph; 6, identifier:node_id; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, expression_statement; 11, if_statement; 12, for_statement; 13, return_statement; 14, identifier:debug; 15, False; 16, comment:"""
returns all the tokens that are dominated or in a span relation with
the given node. If debug is set to True, you'll get a warning if the
graph is cyclic.
Returns
-------
span : list of str
sorted list of token nodes (token node IDs)
"""; 17, boolean_operator; 18, block; 19, assignment; 20, comparison_operator:docgraph.ns+':token' in docgraph.node[node_id]; 21, block; 22, pattern_list; 23, call; 24, block; 25, call; 26, comparison_operator:debug is True; 27, comparison_operator:is_directed_acyclic_graph(docgraph) is False; 28, expression_statement; 29, identifier:span; 30, list; 31, binary_operator:docgraph.ns+':token'; 32, subscript; 33, expression_statement; 34, identifier:src_id; 35, identifier:target_id; 36, identifier:edge_attribs; 37, attribute; 38, argument_list; 39, if_statement; 40, comment:# ignore pointing relations; 41, if_statement; 42, identifier:sorted; 43, argument_list; 44, identifier:debug; 45, True; 46, call; 47, False; 48, call; 49, attribute; 50, string; 51, attribute; 52, identifier:node_id; 53, call; 54, identifier:docgraph; 55, identifier:out_edges_iter; 56, identifier:node_id; 57, keyword_argument; 58, comparison_operator:src_id == target_id; 59, block; 60, comparison_operator:edge_attribs['edge_type'] != EdgeTypes.pointing_relation; 61, block; 62, identifier:span; 63, keyword_argument; 64, identifier:is_directed_acyclic_graph; 65, argument_list; 66, attribute; 67, argument_list; 68, identifier:docgraph; 69, identifier:ns; 70, string_content::token; 71, identifier:docgraph; 72, identifier:node; 73, attribute; 74, argument_list; 75, identifier:data; 76, True; 77, identifier:src_id; 78, identifier:target_id; 79, continue_statement; 80, comment:# ignore self-loops; 81, subscript; 82, attribute; 83, expression_statement; 84, identifier:key; 85, identifier:natural_sort_key; 86, identifier:docgraph; 87, identifier:warnings; 88, identifier:warn; 89, call; 90, identifier:span; 91, identifier:append; 92, identifier:node_id; 93, identifier:edge_attribs; 94, string; 95, identifier:EdgeTypes; 96, identifier:pointing_relation; 97, call; 98, attribute; 99, argument_list; 100, string_content:edge_type; 101, attribute; 102, argument_list; 103, parenthesized_expression; 104, identifier:format; 105, identifier:node_id; 106, identifier:docgraph; 107, identifier:span; 108, identifier:extend; 109, call; 110, concatenated_string; 111, identifier:get_span; 112, argument_list; 113, string:"Can't reliably extract span '{0}' from cyclical graph'{1}'."; 114, string:"Maximum recursion depth may be exceeded."; 115, identifier:docgraph; 116, identifier:target_id | 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; 9, 18; 10, 19; 11, 20; 11, 21; 12, 22; 12, 23; 12, 24; 13, 25; 17, 26; 17, 27; 18, 28; 19, 29; 19, 30; 20, 31; 20, 32; 21, 33; 22, 34; 22, 35; 22, 36; 23, 37; 23, 38; 24, 39; 24, 40; 24, 41; 25, 42; 25, 43; 26, 44; 26, 45; 27, 46; 27, 47; 28, 48; 31, 49; 31, 50; 32, 51; 32, 52; 33, 53; 37, 54; 37, 55; 38, 56; 38, 57; 39, 58; 39, 59; 41, 60; 41, 61; 43, 62; 43, 63; 46, 64; 46, 65; 48, 66; 48, 67; 49, 68; 49, 69; 50, 70; 51, 71; 51, 72; 53, 73; 53, 74; 57, 75; 57, 76; 58, 77; 58, 78; 59, 79; 59, 80; 60, 81; 60, 82; 61, 83; 63, 84; 63, 85; 65, 86; 66, 87; 66, 88; 67, 89; 73, 90; 73, 91; 74, 92; 81, 93; 81, 94; 82, 95; 82, 96; 83, 97; 89, 98; 89, 99; 94, 100; 97, 101; 97, 102; 98, 103; 98, 104; 99, 105; 99, 106; 101, 107; 101, 108; 102, 109; 103, 110; 109, 111; 109, 112; 110, 113; 110, 114; 112, 115; 112, 116 | def get_span(docgraph, node_id, debug=False):
"""
returns all the tokens that are dominated or in a span relation with
the given node. If debug is set to True, you'll get a warning if the
graph is cyclic.
Returns
-------
span : list of str
sorted list of token nodes (token node IDs)
"""
if debug is True and is_directed_acyclic_graph(docgraph) is False:
warnings.warn(
("Can't reliably extract span '{0}' from cyclical graph'{1}'."
"Maximum recursion depth may be exceeded.").format(node_id,
docgraph))
span = []
if docgraph.ns+':token' in docgraph.node[node_id]:
span.append(node_id)
for src_id, target_id, edge_attribs in docgraph.out_edges_iter(node_id,
data=True):
if src_id == target_id:
continue # ignore self-loops
# ignore pointing relations
if edge_attribs['edge_type'] != EdgeTypes.pointing_relation:
span.extend(get_span(docgraph, target_id))
return sorted(span, key=natural_sort_key) |
0, module; 1, function_definition; 2, function_name:_get_terminals_and_nonterminals; 3, parameters; 4, block; 5, identifier:sentence_graph; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""
Given a TigerSentenceGraph, returns a sorted list of terminal node
IDs, as well as a sorted list of nonterminal node IDs.
Parameters
----------
sentence_graph : TigerSentenceGraph
a directed graph representing one syntax annotated sentence from
a TigerXML file
Returns
-------
terminals, nonterminals : list of str
a sorted list of terminal node IDs and a sorted list of
nonterminal node IDs
"""; 12, assignment; 13, assignment; 14, identifier:node_id; 15, call; 16, block; 17, expression_list; 18, identifier:terminals; 19, call; 20, identifier:nonterminals; 21, call; 22, attribute; 23, argument_list; 24, if_statement; 25, call; 26, line_continuation:\; 27, call; 28, identifier:set; 29, argument_list; 30, identifier:set; 31, argument_list; 32, identifier:sentence_graph; 33, identifier:nodes_iter; 34, comparison_operator:sentence_graph.out_degree(node_id) > 0; 35, comment:# all nonterminals (incl. root); 36, block; 37, else_clause; 38, identifier:sorted; 39, argument_list; 40, identifier:sorted; 41, argument_list; 42, call; 43, integer:0; 44, expression_statement; 45, comment:# terminals; 46, block; 47, call; 48, keyword_argument; 49, call; 50, keyword_argument; 51, attribute; 52, argument_list; 53, call; 54, expression_statement; 55, identifier:list; 56, argument_list; 57, identifier:key; 58, identifier:natural_sort_key; 59, identifier:list; 60, argument_list; 61, identifier:key; 62, identifier:natural_sort_key; 63, identifier:sentence_graph; 64, identifier:out_degree; 65, identifier:node_id; 66, attribute; 67, argument_list; 68, call; 69, identifier:terminals; 70, identifier:nonterminals; 71, identifier:nonterminals; 72, identifier:add; 73, identifier:node_id; 74, attribute; 75, argument_list; 76, identifier:terminals; 77, identifier:add; 78, identifier:node_id | 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; 9, 16; 10, 17; 12, 18; 12, 19; 13, 20; 13, 21; 15, 22; 15, 23; 16, 24; 17, 25; 17, 26; 17, 27; 19, 28; 19, 29; 21, 30; 21, 31; 22, 32; 22, 33; 24, 34; 24, 35; 24, 36; 24, 37; 25, 38; 25, 39; 27, 40; 27, 41; 34, 42; 34, 43; 36, 44; 37, 45; 37, 46; 39, 47; 39, 48; 41, 49; 41, 50; 42, 51; 42, 52; 44, 53; 46, 54; 47, 55; 47, 56; 48, 57; 48, 58; 49, 59; 49, 60; 50, 61; 50, 62; 51, 63; 51, 64; 52, 65; 53, 66; 53, 67; 54, 68; 56, 69; 60, 70; 66, 71; 66, 72; 67, 73; 68, 74; 68, 75; 74, 76; 74, 77; 75, 78 | def _get_terminals_and_nonterminals(sentence_graph):
"""
Given a TigerSentenceGraph, returns a sorted list of terminal node
IDs, as well as a sorted list of nonterminal node IDs.
Parameters
----------
sentence_graph : TigerSentenceGraph
a directed graph representing one syntax annotated sentence from
a TigerXML file
Returns
-------
terminals, nonterminals : list of str
a sorted list of terminal node IDs and a sorted list of
nonterminal node IDs
"""
terminals = set()
nonterminals = set()
for node_id in sentence_graph.nodes_iter():
if sentence_graph.out_degree(node_id) > 0:
# all nonterminals (incl. root)
nonterminals.add(node_id)
else: # terminals
terminals.add(node_id)
return sorted(list(terminals), key=natural_sort_key), \
sorted(list(nonterminals), key=natural_sort_key) |
0, module; 1, function_definition; 2, function_name:print_sorted_counter; 3, parameters; 4, block; 5, identifier:counter; 6, default_parameter; 7, expression_statement; 8, for_statement; 9, identifier:tab; 10, integer:1; 11, comment:"""print all elements of a counter in descending order"""; 12, pattern_list; 13, call; 14, block; 15, identifier:key; 16, identifier:count; 17, identifier:sorted; 18, argument_list; 19, print_statement; 20, call; 21, keyword_argument; 22, keyword_argument; 23, call; 24, attribute; 25, argument_list; 26, identifier:key; 27, call; 28, identifier:reverse; 29, True; 30, attribute; 31, argument_list; 32, identifier:counter; 33, identifier:items; 34, identifier:itemgetter; 35, argument_list; 36, string:"{0}{1} - {2}"; 37, identifier:format; 38, binary_operator:'\t'*tab; 39, identifier:key; 40, identifier:count; 41, integer:1; 42, string; 43, identifier:tab; 44, string_content; 45, escape_sequence:\t | 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; 12, 15; 12, 16; 13, 17; 13, 18; 14, 19; 18, 20; 18, 21; 18, 22; 19, 23; 20, 24; 20, 25; 21, 26; 21, 27; 22, 28; 22, 29; 23, 30; 23, 31; 24, 32; 24, 33; 27, 34; 27, 35; 30, 36; 30, 37; 31, 38; 31, 39; 31, 40; 35, 41; 38, 42; 38, 43; 42, 44; 44, 45 | def print_sorted_counter(counter, tab=1):
"""print all elements of a counter in descending order"""
for key, count in sorted(counter.items(), key=itemgetter(1), reverse=True):
print "{0}{1} - {2}".format('\t'*tab, key, count) |
0, module; 1, function_definition; 2, function_name:sorted_bfs_edges; 3, parameters; 4, block; 5, identifier:G; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, while_statement; 14, identifier:source; 15, None; 16, comment:"""Produce edges in a breadth-first-search starting at source.
Neighbors appear in the order a linguist would expect in a syntax tree.
The result will only contain edges that express a dominance or spanning
relation, i.e. edges expressing pointing or precedence relations will
be ignored.
Parameters
----------
G : DiscourseDocumentGraph
source : node
Specify starting node for breadth-first search and return edges in
the component reachable from source.
Returns
-------
edges: generator
A generator of edges in the breadth-first-search.
"""; 17, comparison_operator:source is None; 18, block; 19, assignment; 20, assignment; 21, assignment; 22, assignment; 23, identifier:queue; 24, block; 25, identifier:source; 26, None; 27, expression_statement; 28, identifier:xpos; 29, call; 30, identifier:visited; 31, call; 32, identifier:source_children; 33, call; 34, identifier:queue; 35, call; 36, expression_statement; 37, try_statement; 38, assignment; 39, identifier:horizontal_positions; 40, argument_list; 41, identifier:set; 42, argument_list; 43, identifier:get_child_nodes; 44, argument_list; 45, identifier:deque; 46, argument_list; 47, assignment; 48, block; 49, except_clause; 50, identifier:source; 51, attribute; 52, identifier:G; 53, identifier:source; 54, list; 55, identifier:G; 56, identifier:source; 57, list; 58, pattern_list; 59, subscript; 60, expression_statement; 61, if_statement; 62, identifier:StopIteration; 63, block; 64, identifier:G; 65, identifier:root; 66, identifier:source; 67, tuple; 68, identifier:parent; 69, identifier:children; 70, identifier:queue; 71, integer:0; 72, assignment; 73, comparison_operator:child not in visited; 74, block; 75, expression_statement; 76, identifier:source; 77, call; 78, identifier:child; 79, call; 80, identifier:child; 81, identifier:visited; 82, expression_statement; 83, expression_statement; 84, expression_statement; 85, expression_statement; 86, call; 87, identifier:iter; 88, argument_list; 89, identifier:next; 90, argument_list; 91, yield; 92, call; 93, assignment; 94, call; 95, attribute; 96, argument_list; 97, call; 98, identifier:children; 99, expression_list; 100, attribute; 101, argument_list; 102, identifier:grandchildren; 103, call; 104, attribute; 105, argument_list; 106, identifier:queue; 107, identifier:popleft; 108, identifier:sorted; 109, argument_list; 110, identifier:parent; 111, identifier:child; 112, identifier:visited; 113, identifier:add; 114, identifier:child; 115, identifier:get_child_nodes; 116, argument_list; 117, identifier:queue; 118, identifier:append; 119, tuple; 120, identifier:source_children; 121, keyword_argument; 122, identifier:G; 123, identifier:child; 124, identifier:child; 125, call; 126, identifier:key; 127, lambda; 128, identifier:iter; 129, argument_list; 130, lambda_parameters; 131, subscript; 132, call; 133, identifier:x; 134, identifier:xpos; 135, identifier:x; 136, identifier:sorted; 137, argument_list; 138, identifier:grandchildren; 139, keyword_argument; 140, identifier:key; 141, lambda; 142, lambda_parameters; 143, subscript; 144, identifier:x; 145, identifier:xpos; 146, identifier:x | 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; 12, 22; 13, 23; 13, 24; 17, 25; 17, 26; 18, 27; 19, 28; 19, 29; 20, 30; 20, 31; 21, 32; 21, 33; 22, 34; 22, 35; 24, 36; 24, 37; 27, 38; 29, 39; 29, 40; 31, 41; 31, 42; 33, 43; 33, 44; 35, 45; 35, 46; 36, 47; 37, 48; 37, 49; 38, 50; 38, 51; 40, 52; 40, 53; 42, 54; 44, 55; 44, 56; 46, 57; 47, 58; 47, 59; 48, 60; 48, 61; 49, 62; 49, 63; 51, 64; 51, 65; 54, 66; 57, 67; 58, 68; 58, 69; 59, 70; 59, 71; 60, 72; 61, 73; 61, 74; 63, 75; 67, 76; 67, 77; 72, 78; 72, 79; 73, 80; 73, 81; 74, 82; 74, 83; 74, 84; 74, 85; 75, 86; 77, 87; 77, 88; 79, 89; 79, 90; 82, 91; 83, 92; 84, 93; 85, 94; 86, 95; 86, 96; 88, 97; 90, 98; 91, 99; 92, 100; 92, 101; 93, 102; 93, 103; 94, 104; 94, 105; 95, 106; 95, 107; 97, 108; 97, 109; 99, 110; 99, 111; 100, 112; 100, 113; 101, 114; 103, 115; 103, 116; 104, 117; 104, 118; 105, 119; 109, 120; 109, 121; 116, 122; 116, 123; 119, 124; 119, 125; 121, 126; 121, 127; 125, 128; 125, 129; 127, 130; 127, 131; 129, 132; 130, 133; 131, 134; 131, 135; 132, 136; 132, 137; 137, 138; 137, 139; 139, 140; 139, 141; 141, 142; 141, 143; 142, 144; 143, 145; 143, 146 | def sorted_bfs_edges(G, source=None):
"""Produce edges in a breadth-first-search starting at source.
Neighbors appear in the order a linguist would expect in a syntax tree.
The result will only contain edges that express a dominance or spanning
relation, i.e. edges expressing pointing or precedence relations will
be ignored.
Parameters
----------
G : DiscourseDocumentGraph
source : node
Specify starting node for breadth-first search and return edges in
the component reachable from source.
Returns
-------
edges: generator
A generator of edges in the breadth-first-search.
"""
if source is None:
source = G.root
xpos = horizontal_positions(G, source)
visited = set([source])
source_children = get_child_nodes(G, source)
queue = deque([(source, iter(sorted(source_children,
key=lambda x: xpos[x])))])
while queue:
parent, children = queue[0]
try:
child = next(children)
if child not in visited:
yield parent, child
visited.add(child)
grandchildren = get_child_nodes(G, child)
queue.append((child, iter(sorted(grandchildren,
key=lambda x: xpos[x]))))
except StopIteration:
queue.popleft() |
0, module; 1, function_definition; 2, function_name:sorted_bfs_successors; 3, parameters; 4, block; 5, identifier:G; 6, default_parameter; 7, expression_statement; 8, if_statement; 9, expression_statement; 10, for_statement; 11, return_statement; 12, identifier:source; 13, None; 14, comment:"""Return dictionary of successors in breadth-first-search from source.
Parameters
----------
G : DiscourseDocumentGraph graph
source : node
Specify starting node for breadth-first search and return edges in
the component reachable from source.
Returns
-------
successors: dict
A dictionary with nodes as keys and list of succssors nodes as values.
"""; 15, comparison_operator:source is None; 16, block; 17, assignment; 18, pattern_list; 19, call; 20, block; 21, call; 22, identifier:source; 23, None; 24, expression_statement; 25, identifier:successors; 26, call; 27, identifier:src; 28, identifier:target; 29, identifier:sorted_bfs_edges; 30, argument_list; 31, expression_statement; 32, identifier:dict; 33, argument_list; 34, assignment; 35, identifier:defaultdict; 36, argument_list; 37, identifier:G; 38, identifier:source; 39, call; 40, identifier:successors; 41, identifier:source; 42, attribute; 43, identifier:list; 44, attribute; 45, argument_list; 46, identifier:G; 47, identifier:root; 48, subscript; 49, identifier:append; 50, identifier:target; 51, identifier:successors; 52, identifier:src | 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; 8, 16; 9, 17; 10, 18; 10, 19; 10, 20; 11, 21; 15, 22; 15, 23; 16, 24; 17, 25; 17, 26; 18, 27; 18, 28; 19, 29; 19, 30; 20, 31; 21, 32; 21, 33; 24, 34; 26, 35; 26, 36; 30, 37; 30, 38; 31, 39; 33, 40; 34, 41; 34, 42; 36, 43; 39, 44; 39, 45; 42, 46; 42, 47; 44, 48; 44, 49; 45, 50; 48, 51; 48, 52 | def sorted_bfs_successors(G, source=None):
"""Return dictionary of successors in breadth-first-search from source.
Parameters
----------
G : DiscourseDocumentGraph graph
source : node
Specify starting node for breadth-first search and return edges in
the component reachable from source.
Returns
-------
successors: dict
A dictionary with nodes as keys and list of succssors nodes as values.
"""
if source is None:
source = G.root
successors = defaultdict(list)
for src, target in sorted_bfs_edges(G, source):
successors[src].append(target)
return dict(successors) |
Subsets and Splits