nodes
stringlengths 501
22.4k
| edges
stringlengths 138
5.07k
| code
stringlengths 108
19.3k
|
---|---|---|
0, module; 1, function_definition; 2, function_name:interev_mag; 3, parameters; 4, block; 5, identifier:times; 6, identifier:mags; 7, default_parameter; 8, dictionary_splat_pattern; 9, expression_statement; 10, import_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, comment:# Make two subplots next to each other of time before and time after; 16, expression_statement; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, for_statement; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, expression_statement; 25, expression_statement; 26, expression_statement; 27, expression_statement; 28, expression_statement; 29, expression_statement; 30, expression_statement; 31, expression_statement; 32, expression_statement; 33, comment:# pragma: no cover; 34, return_statement; 35, identifier:size; 36, tuple; 37, identifier:kwargs; 38, comment:"""
Plot inter-event times against magnitude.
:type times: list
:param times: list of the detection times, must be sorted the same as mags
:type mags: list
:param mags: list of magnitudes
:type size: tuple
:param size: Size of figure in inches.
:returns: :class:`matplotlib.figure.Figure`
.. rubric:: Example
>>> from obspy.clients.fdsn import Client
>>> from obspy import UTCDateTime
>>> from eqcorrscan.utils.plotting import interev_mag
>>> client = Client('IRIS')
>>> t1 = UTCDateTime('2012-03-26T00:00:00')
>>> t2 = t1 + (3 * 86400)
>>> catalog = client.get_events(starttime=t1, endtime=t2, minmagnitude=3)
>>> magnitudes = [event.preferred_magnitude().mag for event in catalog]
>>> times = [event.preferred_origin().time for event in catalog]
>>> interev_mag(times, magnitudes) # doctest: +SKIP
.. plot::
from obspy.clients.fdsn import Client
from obspy import UTCDateTime
from eqcorrscan.utils.plotting import interev_mag
client = Client('IRIS')
t1 = UTCDateTime('2012-03-26T00:00:00')
t2 = t1 + (3 * 86400)
catalog = client.get_events(starttime=t1, endtime=t2, minmagnitude=3)
magnitudes = [event.preferred_magnitude().mag for event in catalog]
times = [event.preferred_origin().time for event in catalog]
interev_mag(times, magnitudes)
"""; 39, aliased_import; 40, assignment; 41, call; 42, assignment; 43, assignment; 44, assignment; 45, assignment; 46, assignment; 47, assignment; 48, identifier:i; 49, call; 50, block; 51, call; 52, call; 53, call; 54, call; 55, call; 56, call; 57, call; 58, call; 59, call; 60, call; 61, call; 62, assignment; 63, identifier:fig; 64, float:10.5; 65, float:7.5; 66, dotted_name; 67, identifier:plt; 68, identifier:info; 69, list_comprehension; 70, attribute; 71, argument_list; 72, identifier:times; 73, list_comprehension; 74, identifier:mags; 75, list_comprehension; 76, pattern_list; 77, call; 78, identifier:axes; 79, call; 80, identifier:pre_times; 81, list; 82, identifier:post_times; 83, list; 84, identifier:range; 85, argument_list; 86, if_statement; 87, if_statement; 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, attribute; 99, argument_list; 100, attribute; 101, argument_list; 102, attribute; 103, argument_list; 104, attribute; 105, argument_list; 106, attribute; 107, argument_list; 108, attribute; 109, argument_list; 110, identifier:fig; 111, call; 112, identifier:matplotlib; 113, identifier:pyplot; 114, tuple; 115, for_in_clause; 116, identifier:info; 117, identifier:sort; 118, keyword_argument; 119, subscript; 120, for_in_clause; 121, subscript; 122, for_in_clause; 123, identifier:fig; 124, identifier:axes; 125, attribute; 126, argument_list; 127, attribute; 128, argument_list; 129, call; 130, comparison_operator:i > 0; 131, block; 132, comparison_operator:i < len(times) - 1; 133, block; 134, subscript; 135, identifier:scatter; 136, identifier:pre_times; 137, subscript; 138, subscript; 139, identifier:set_title; 140, string; 141, subscript; 142, identifier:set_ylabel; 143, string; 144, subscript; 145, identifier:set_xlabel; 146, string; 147, identifier:plt; 148, identifier:setp; 149, call; 150, keyword_argument; 151, subscript; 152, identifier:scatter; 153, identifier:pre_times; 154, subscript; 155, subscript; 156, identifier:set_title; 157, string; 158, subscript; 159, identifier:set_xlabel; 160, string; 161, subscript; 162, identifier:autoscale; 163, keyword_argument; 164, keyword_argument; 165, subscript; 166, identifier:autoscale; 167, keyword_argument; 168, keyword_argument; 169, identifier:plt; 170, identifier:setp; 171, call; 172, keyword_argument; 173, identifier:_finalise_figure; 174, argument_list; 175, subscript; 176, subscript; 177, identifier:i; 178, call; 179, identifier:key; 180, lambda; 181, identifier:x; 182, integer:0; 183, identifier:x; 184, identifier:info; 185, identifier:x; 186, integer:1; 187, identifier:x; 188, identifier:info; 189, identifier:plt; 190, identifier:subplots; 191, integer:1; 192, integer:2; 193, keyword_argument; 194, keyword_argument; 195, identifier:axes; 196, identifier:ravel; 197, identifier:len; 198, argument_list; 199, identifier:i; 200, integer:0; 201, expression_statement; 202, identifier:i; 203, binary_operator:len(times) - 1; 204, expression_statement; 205, identifier:axes; 206, integer:0; 207, identifier:mags; 208, slice; 209, identifier:axes; 210, integer:0; 211, string_content:Pre-event times; 212, identifier:axes; 213, integer:0; 214, string_content:Magnitude; 215, identifier:axes; 216, integer:0; 217, string_content:Time (Minutes); 218, attribute; 219, argument_list; 220, identifier:rotation; 221, integer:30; 222, identifier:axes; 223, integer:1; 224, identifier:mags; 225, slice; 226, identifier:axes; 227, integer:1; 228, string_content:Post-event times; 229, identifier:axes; 230, integer:1; 231, string_content:Time (Minutes); 232, identifier:axes; 233, integer:0; 234, identifier:enable; 235, True; 236, identifier:tight; 237, True; 238, identifier:axes; 239, integer:1; 240, identifier:enable; 241, True; 242, identifier:tight; 243, True; 244, attribute; 245, argument_list; 246, identifier:rotation; 247, integer:30; 248, keyword_argument; 249, dictionary_splat; 250, identifier:times; 251, identifier:i; 252, identifier:mags; 253, identifier:i; 254, identifier:range; 255, argument_list; 256, lambda_parameters; 257, subscript; 258, identifier:sharey; 259, True; 260, identifier:figsize; 261, identifier:size; 262, identifier:times; 263, call; 264, call; 265, integer:1; 266, call; 267, integer:1; 268, attribute; 269, identifier:get_majorticklabels; 270, unary_operator; 271, attribute; 272, identifier:get_majorticklabels; 273, identifier:fig; 274, identifier:fig; 275, identifier:kwargs; 276, call; 277, identifier:tup; 278, identifier:tup; 279, integer:0; 280, attribute; 281, argument_list; 282, identifier:len; 283, argument_list; 284, attribute; 285, argument_list; 286, subscript; 287, identifier:xaxis; 288, integer:1; 289, subscript; 290, identifier:xaxis; 291, identifier:len; 292, argument_list; 293, identifier:pre_times; 294, identifier:append; 295, binary_operator:(times[i] - times[i - 1]) / 60; 296, identifier:times; 297, identifier:post_times; 298, identifier:append; 299, binary_operator:(times[i + 1] - times[i]) / 60; 300, identifier:axes; 301, integer:0; 302, identifier:axes; 303, integer:1; 304, identifier:times; 305, parenthesized_expression; 306, integer:60; 307, parenthesized_expression; 308, integer:60; 309, binary_operator:times[i] - times[i - 1]; 310, binary_operator:times[i + 1] - times[i]; 311, subscript; 312, subscript; 313, subscript; 314, subscript; 315, identifier:times; 316, identifier:i; 317, identifier:times; 318, binary_operator:i - 1; 319, identifier:times; 320, binary_operator:i + 1; 321, identifier:times; 322, identifier:i; 323, identifier:i; 324, integer:1; 325, identifier:i; 326, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 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; 7, 36; 8, 37; 9, 38; 10, 39; 11, 40; 12, 41; 13, 42; 14, 43; 16, 44; 17, 45; 18, 46; 19, 47; 20, 48; 20, 49; 20, 50; 21, 51; 22, 52; 23, 53; 24, 54; 25, 55; 26, 56; 27, 57; 28, 58; 29, 59; 30, 60; 31, 61; 32, 62; 34, 63; 36, 64; 36, 65; 39, 66; 39, 67; 40, 68; 40, 69; 41, 70; 41, 71; 42, 72; 42, 73; 43, 74; 43, 75; 44, 76; 44, 77; 45, 78; 45, 79; 46, 80; 46, 81; 47, 82; 47, 83; 49, 84; 49, 85; 50, 86; 50, 87; 51, 88; 51, 89; 52, 90; 52, 91; 53, 92; 53, 93; 54, 94; 54, 95; 55, 96; 55, 97; 56, 98; 56, 99; 57, 100; 57, 101; 58, 102; 58, 103; 59, 104; 59, 105; 60, 106; 60, 107; 61, 108; 61, 109; 62, 110; 62, 111; 66, 112; 66, 113; 69, 114; 69, 115; 70, 116; 70, 117; 71, 118; 73, 119; 73, 120; 75, 121; 75, 122; 76, 123; 76, 124; 77, 125; 77, 126; 79, 127; 79, 128; 85, 129; 86, 130; 86, 131; 87, 132; 87, 133; 88, 134; 88, 135; 89, 136; 89, 137; 90, 138; 90, 139; 91, 140; 92, 141; 92, 142; 93, 143; 94, 144; 94, 145; 95, 146; 96, 147; 96, 148; 97, 149; 97, 150; 98, 151; 98, 152; 99, 153; 99, 154; 100, 155; 100, 156; 101, 157; 102, 158; 102, 159; 103, 160; 104, 161; 104, 162; 105, 163; 105, 164; 106, 165; 106, 166; 107, 167; 107, 168; 108, 169; 108, 170; 109, 171; 109, 172; 111, 173; 111, 174; 114, 175; 114, 176; 115, 177; 115, 178; 118, 179; 118, 180; 119, 181; 119, 182; 120, 183; 120, 184; 121, 185; 121, 186; 122, 187; 122, 188; 125, 189; 125, 190; 126, 191; 126, 192; 126, 193; 126, 194; 127, 195; 127, 196; 129, 197; 129, 198; 130, 199; 130, 200; 131, 201; 132, 202; 132, 203; 133, 204; 134, 205; 134, 206; 137, 207; 137, 208; 138, 209; 138, 210; 140, 211; 141, 212; 141, 213; 143, 214; 144, 215; 144, 216; 146, 217; 149, 218; 149, 219; 150, 220; 150, 221; 151, 222; 151, 223; 154, 224; 154, 225; 155, 226; 155, 227; 157, 228; 158, 229; 158, 230; 160, 231; 161, 232; 161, 233; 163, 234; 163, 235; 164, 236; 164, 237; 165, 238; 165, 239; 167, 240; 167, 241; 168, 242; 168, 243; 171, 244; 171, 245; 172, 246; 172, 247; 174, 248; 174, 249; 175, 250; 175, 251; 176, 252; 176, 253; 178, 254; 178, 255; 180, 256; 180, 257; 193, 258; 193, 259; 194, 260; 194, 261; 198, 262; 201, 263; 203, 264; 203, 265; 204, 266; 208, 267; 218, 268; 218, 269; 225, 270; 244, 271; 244, 272; 248, 273; 248, 274; 249, 275; 255, 276; 256, 277; 257, 278; 257, 279; 263, 280; 263, 281; 264, 282; 264, 283; 266, 284; 266, 285; 268, 286; 268, 287; 270, 288; 271, 289; 271, 290; 276, 291; 276, 292; 280, 293; 280, 294; 281, 295; 283, 296; 284, 297; 284, 298; 285, 299; 286, 300; 286, 301; 289, 302; 289, 303; 292, 304; 295, 305; 295, 306; 299, 307; 299, 308; 305, 309; 307, 310; 309, 311; 309, 312; 310, 313; 310, 314; 311, 315; 311, 316; 312, 317; 312, 318; 313, 319; 313, 320; 314, 321; 314, 322; 318, 323; 318, 324; 320, 325; 320, 326 | def interev_mag(times, mags, size=(10.5, 7.5), **kwargs):
"""
Plot inter-event times against magnitude.
:type times: list
:param times: list of the detection times, must be sorted the same as mags
:type mags: list
:param mags: list of magnitudes
:type size: tuple
:param size: Size of figure in inches.
:returns: :class:`matplotlib.figure.Figure`
.. rubric:: Example
>>> from obspy.clients.fdsn import Client
>>> from obspy import UTCDateTime
>>> from eqcorrscan.utils.plotting import interev_mag
>>> client = Client('IRIS')
>>> t1 = UTCDateTime('2012-03-26T00:00:00')
>>> t2 = t1 + (3 * 86400)
>>> catalog = client.get_events(starttime=t1, endtime=t2, minmagnitude=3)
>>> magnitudes = [event.preferred_magnitude().mag for event in catalog]
>>> times = [event.preferred_origin().time for event in catalog]
>>> interev_mag(times, magnitudes) # doctest: +SKIP
.. plot::
from obspy.clients.fdsn import Client
from obspy import UTCDateTime
from eqcorrscan.utils.plotting import interev_mag
client = Client('IRIS')
t1 = UTCDateTime('2012-03-26T00:00:00')
t2 = t1 + (3 * 86400)
catalog = client.get_events(starttime=t1, endtime=t2, minmagnitude=3)
magnitudes = [event.preferred_magnitude().mag for event in catalog]
times = [event.preferred_origin().time for event in catalog]
interev_mag(times, magnitudes)
"""
import matplotlib.pyplot as plt
info = [(times[i], mags[i]) for i in range(len(times))]
info.sort(key=lambda tup: tup[0])
times = [x[0] for x in info]
mags = [x[1] for x in info]
# Make two subplots next to each other of time before and time after
fig, axes = plt.subplots(1, 2, sharey=True, figsize=size)
axes = axes.ravel()
pre_times = []
post_times = []
for i in range(len(times)):
if i > 0:
pre_times.append((times[i] - times[i - 1]) / 60)
if i < len(times) - 1:
post_times.append((times[i + 1] - times[i]) / 60)
axes[0].scatter(pre_times, mags[1:])
axes[0].set_title('Pre-event times')
axes[0].set_ylabel('Magnitude')
axes[0].set_xlabel('Time (Minutes)')
plt.setp(axes[0].xaxis.get_majorticklabels(), rotation=30)
axes[1].scatter(pre_times, mags[:-1])
axes[1].set_title('Post-event times')
axes[1].set_xlabel('Time (Minutes)')
axes[0].autoscale(enable=True, tight=True)
axes[1].autoscale(enable=True, tight=True)
plt.setp(axes[1].xaxis.get_majorticklabels(), rotation=30)
fig = _finalise_figure(fig=fig, **kwargs) # pragma: no cover
return fig |
0, module; 1, function_definition; 2, function_name:pprint_blockers; 3, parameters; 4, block; 5, identifier:blockers; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""Pretty print blockers into a sequence of strings.
Results will be sorted by top-level project name. This means that if a
project is blocking another project then the dependent project will be
what is used in the sorting, not the project at the bottom of the
dependency graph.
"""; 11, assignment; 12, identifier:blocker; 13, call; 14, block; 15, identifier:pprinted; 16, identifier:pprinted; 17, list; 18, identifier:sorted; 19, argument_list; 20, expression_statement; 21, if_statement; 22, expression_statement; 23, identifier:blockers; 24, keyword_argument; 25, assignment; 26, comparison_operator:len(blocker) > 1; 27, block; 28, call; 29, identifier:key; 30, lambda; 31, identifier:buf; 32, list; 33, call; 34, integer:1; 35, expression_statement; 36, expression_statement; 37, expression_statement; 38, attribute; 39, argument_list; 40, lambda_parameters; 41, call; 42, subscript; 43, identifier:len; 44, argument_list; 45, call; 46, call; 47, call; 48, identifier:pprinted; 49, identifier:append; 50, call; 51, identifier:x; 52, identifier:tuple; 53, argument_list; 54, identifier:blocker; 55, integer:0; 56, identifier:blocker; 57, attribute; 58, argument_list; 59, attribute; 60, argument_list; 61, attribute; 62, argument_list; 63, attribute; 64, argument_list; 65, call; 66, identifier:buf; 67, identifier:append; 68, string; 69, identifier:buf; 70, identifier:append; 71, call; 72, identifier:buf; 73, identifier:append; 74, string; 75, string; 76, identifier:join; 77, identifier:buf; 78, identifier:reversed; 79, argument_list; 80, string_content:(which is blocking; 81, attribute; 82, argument_list; 83, string_content:); 84, identifier:x; 85, string; 86, identifier:join; 87, subscript; 88, string_content:, which is blocking; 89, identifier:blocker; 90, slice; 91, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 8, 14; 9, 15; 11, 16; 11, 17; 13, 18; 13, 19; 14, 20; 14, 21; 14, 22; 19, 23; 19, 24; 20, 25; 21, 26; 21, 27; 22, 28; 24, 29; 24, 30; 25, 31; 25, 32; 26, 33; 26, 34; 27, 35; 27, 36; 27, 37; 28, 38; 28, 39; 30, 40; 30, 41; 32, 42; 33, 43; 33, 44; 35, 45; 36, 46; 37, 47; 38, 48; 38, 49; 39, 50; 40, 51; 41, 52; 41, 53; 42, 54; 42, 55; 44, 56; 45, 57; 45, 58; 46, 59; 46, 60; 47, 61; 47, 62; 50, 63; 50, 64; 53, 65; 57, 66; 57, 67; 58, 68; 59, 69; 59, 70; 60, 71; 61, 72; 61, 73; 62, 74; 63, 75; 63, 76; 64, 77; 65, 78; 65, 79; 68, 80; 71, 81; 71, 82; 74, 83; 79, 84; 81, 85; 81, 86; 82, 87; 85, 88; 87, 89; 87, 90; 90, 91 | def pprint_blockers(blockers):
"""Pretty print blockers into a sequence of strings.
Results will be sorted by top-level project name. This means that if a
project is blocking another project then the dependent project will be
what is used in the sorting, not the project at the bottom of the
dependency graph.
"""
pprinted = []
for blocker in sorted(blockers, key=lambda x: tuple(reversed(x))):
buf = [blocker[0]]
if len(blocker) > 1:
buf.append(' (which is blocking ')
buf.append(', which is blocking '.join(blocker[1:]))
buf.append(')')
pprinted.append(''.join(buf))
return pprinted |
0, module; 1, function_definition; 2, function_name:get_document_summary; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, if_statement; 13, expression_statement; 14, for_statement; 15, return_statement; 16, identifier:N; 17, None; 18, identifier:cite_sort; 19, True; 20, identifier:refresh; 21, True; 22, comment:"""Return a summary string of documents.
Parameters
----------
N : int or None (optional, default=None)
Maximum number of documents to include in the summary.
If None, return all documents.
cite_sort : bool (optional, default=True)
Whether to sort xml by number of citations, in decreasing order,
or not.
refresh : bool (optional, default=True)
Whether to refresh the cached abstract file (if it exists) or not.
Returns
-------
s : str
Text summarizing an author's documents.
"""; 23, assignment; 24, identifier:cite_sort; 25, block; 26, comparison_operator:N is None; 27, block; 28, assignment; 29, identifier:i; 30, call; 31, block; 32, call; 33, identifier:abstracts; 34, call; 35, expression_statement; 36, expression_statement; 37, expression_statement; 38, identifier:N; 39, None; 40, expression_statement; 41, identifier:s; 42, list; 43, identifier:range; 44, argument_list; 45, expression_statement; 46, attribute; 47, argument_list; 48, attribute; 49, argument_list; 50, assignment; 51, call; 52, assignment; 53, assignment; 54, call; 55, identifier:N; 56, augmented_assignment; 57, string; 58, identifier:join; 59, identifier:s; 60, identifier:self; 61, identifier:get_abstracts; 62, keyword_argument; 63, identifier:counts; 64, list_comprehension; 65, attribute; 66, argument_list; 67, identifier:abstracts; 68, list_comprehension; 69, identifier:N; 70, call; 71, attribute; 72, argument_list; 73, identifier:s; 74, list; 75, string_content; 76, identifier:refresh; 77, identifier:refresh; 78, tuple; 79, for_in_clause; 80, identifier:counts; 81, identifier:sort; 82, keyword_argument; 83, keyword_argument; 84, subscript; 85, for_in_clause; 86, identifier:len; 87, argument_list; 88, string; 89, identifier:format; 90, identifier:N; 91, call; 92, call; 93, escape_sequence:\n; 94, identifier:a; 95, call; 96, identifier:a; 97, identifier:abstracts; 98, identifier:reverse; 99, True; 100, identifier:key; 101, call; 102, identifier:a; 103, integer:0; 104, identifier:a; 105, identifier:counts; 106, identifier:abstracts; 107, string_content:{0} of {1} documents; 108, identifier:len; 109, argument_list; 110, attribute; 111, argument_list; 112, identifier:int; 113, argument_list; 114, identifier:itemgetter; 115, argument_list; 116, identifier:abstracts; 117, string; 118, identifier:format; 119, binary_operator:i + 1; 120, call; 121, attribute; 122, integer:1; 123, string_content; 124, identifier:i; 125, integer:1; 126, identifier:str; 127, argument_list; 128, identifier:a; 129, identifier:citedby_count; 130, escape_sequence:\n; 131, subscript; 132, identifier:abstracts; 133, identifier:i | 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; 12, 26; 12, 27; 13, 28; 14, 29; 14, 30; 14, 31; 15, 32; 23, 33; 23, 34; 25, 35; 25, 36; 25, 37; 26, 38; 26, 39; 27, 40; 28, 41; 28, 42; 30, 43; 30, 44; 31, 45; 32, 46; 32, 47; 34, 48; 34, 49; 35, 50; 36, 51; 37, 52; 40, 53; 42, 54; 44, 55; 45, 56; 46, 57; 46, 58; 47, 59; 48, 60; 48, 61; 49, 62; 50, 63; 50, 64; 51, 65; 51, 66; 52, 67; 52, 68; 53, 69; 53, 70; 54, 71; 54, 72; 56, 73; 56, 74; 57, 75; 62, 76; 62, 77; 64, 78; 64, 79; 65, 80; 65, 81; 66, 82; 66, 83; 68, 84; 68, 85; 70, 86; 70, 87; 71, 88; 71, 89; 72, 90; 72, 91; 74, 92; 75, 93; 78, 94; 78, 95; 79, 96; 79, 97; 82, 98; 82, 99; 83, 100; 83, 101; 84, 102; 84, 103; 85, 104; 85, 105; 87, 106; 88, 107; 91, 108; 91, 109; 92, 110; 92, 111; 95, 112; 95, 113; 101, 114; 101, 115; 109, 116; 110, 117; 110, 118; 111, 119; 111, 120; 113, 121; 115, 122; 117, 123; 119, 124; 119, 125; 120, 126; 120, 127; 121, 128; 121, 129; 123, 130; 127, 131; 131, 132; 131, 133 | def get_document_summary(self, N=None, cite_sort=True, refresh=True):
"""Return a summary string of documents.
Parameters
----------
N : int or None (optional, default=None)
Maximum number of documents to include in the summary.
If None, return all documents.
cite_sort : bool (optional, default=True)
Whether to sort xml by number of citations, in decreasing order,
or not.
refresh : bool (optional, default=True)
Whether to refresh the cached abstract file (if it exists) or not.
Returns
-------
s : str
Text summarizing an author's documents.
"""
abstracts = self.get_abstracts(refresh=refresh)
if cite_sort:
counts = [(a, int(a.citedby_count)) for a in abstracts]
counts.sort(reverse=True, key=itemgetter(1))
abstracts = [a[0] for a in counts]
if N is None:
N = len(abstracts)
s = [u'{0} of {1} documents'.format(N, len(abstracts))]
for i in range(N):
s += ['{0:2d}. {1}\n'.format(i + 1, str(abstracts[i]))]
return '\n'.join(s) |
0, module; 1, function_definition; 2, function_name:_match_version_string; 3, parameters; 4, block; 5, identifier:version; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, comment:# If, for whatever reason, the binary didn't tell us its version, then; 11, comment:# these might be (None, None, None), and so we should avoid typecasting; 12, comment:# them when that is the case.; 13, if_statement; 14, return_statement; 15, comment:"""Sort a binary version string into major, minor, and micro integers.
:param str version: A version string in the form x.x.x
:raises GnuPGVersionError: if the **version** string couldn't be parsed.
:rtype: tuple
:returns: A 3-tuple of integers, representing the (MAJOR, MINOR, MICRO)
version numbers. For example::
_match_version_string("2.1.3")
would return ``(2, 1, 3)``.
"""; 16, assignment; 17, assignment; 18, assignment; 19, boolean_operator; 20, block; 21, else_clause; 22, tuple; 23, identifier:matched; 24, call; 25, identifier:g; 26, call; 27, pattern_list; 28, expression_list; 29, boolean_operator; 30, identifier:micro; 31, expression_statement; 32, block; 33, identifier:major; 34, identifier:minor; 35, identifier:micro; 36, attribute; 37, argument_list; 38, attribute; 39, argument_list; 40, identifier:major; 41, identifier:minor; 42, identifier:micro; 43, subscript; 44, subscript; 45, subscript; 46, identifier:major; 47, identifier:minor; 48, assignment; 49, raise_statement; 50, identifier:_VERSION_STRING_REGEX; 51, identifier:match; 52, identifier:version; 53, identifier:matched; 54, identifier:groups; 55, identifier:g; 56, integer:0; 57, identifier:g; 58, integer:2; 59, identifier:g; 60, integer:4; 61, pattern_list; 62, expression_list; 63, call; 64, identifier:major; 65, identifier:minor; 66, identifier:micro; 67, call; 68, call; 69, call; 70, identifier:GnuPGVersionError; 71, argument_list; 72, identifier:int; 73, argument_list; 74, identifier:int; 75, argument_list; 76, identifier:int; 77, argument_list; 78, binary_operator:"Could not parse GnuPG version from: %r" %
version; 79, identifier:major; 80, identifier:minor; 81, identifier:micro; 82, string:"Could not parse GnuPG version from: %r"; 83, identifier:version | 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; 13, 19; 13, 20; 13, 21; 14, 22; 16, 23; 16, 24; 17, 25; 17, 26; 18, 27; 18, 28; 19, 29; 19, 30; 20, 31; 21, 32; 22, 33; 22, 34; 22, 35; 24, 36; 24, 37; 26, 38; 26, 39; 27, 40; 27, 41; 27, 42; 28, 43; 28, 44; 28, 45; 29, 46; 29, 47; 31, 48; 32, 49; 36, 50; 36, 51; 37, 52; 38, 53; 38, 54; 43, 55; 43, 56; 44, 57; 44, 58; 45, 59; 45, 60; 48, 61; 48, 62; 49, 63; 61, 64; 61, 65; 61, 66; 62, 67; 62, 68; 62, 69; 63, 70; 63, 71; 67, 72; 67, 73; 68, 74; 68, 75; 69, 76; 69, 77; 71, 78; 73, 79; 75, 80; 77, 81; 78, 82; 78, 83 | def _match_version_string(version):
"""Sort a binary version string into major, minor, and micro integers.
:param str version: A version string in the form x.x.x
:raises GnuPGVersionError: if the **version** string couldn't be parsed.
:rtype: tuple
:returns: A 3-tuple of integers, representing the (MAJOR, MINOR, MICRO)
version numbers. For example::
_match_version_string("2.1.3")
would return ``(2, 1, 3)``.
"""
matched = _VERSION_STRING_REGEX.match(version)
g = matched.groups()
major, minor, micro = g[0], g[2], g[4]
# If, for whatever reason, the binary didn't tell us its version, then
# these might be (None, None, None), and so we should avoid typecasting
# them when that is the case.
if major and minor and micro:
major, minor, micro = int(major), int(minor), int(micro)
else:
raise GnuPGVersionError("Could not parse GnuPG version from: %r" %
version)
return (major, minor, micro) |
0, module; 1, function_definition; 2, function_name:generate_help; 3, parameters; 4, block; 5, expression_statement; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""Generates help text with alphabetically sorted recipes."""; 11, assignment; 12, assignment; 13, pattern_list; 14, call; 15, block; 16, identifier:help_text; 17, identifier:help_text; 18, string; 19, identifier:recipes; 20, call; 21, identifier:contents; 22, identifier:_; 23, identifier:_; 24, identifier:sorted; 25, argument_list; 26, expression_statement; 27, string_content; 28, attribute; 29, argument_list; 30, identifier:recipes; 31, keyword_argument; 32, augmented_assignment; 33, escape_sequence:\n; 34, escape_sequence:\n; 35, escape_sequence:\n; 36, attribute; 37, identifier:get_registered_recipes; 38, identifier:key; 39, lambda; 40, identifier:help_text; 41, call; 42, identifier:config; 43, identifier:Config; 44, lambda_parameters; 45, subscript; 46, attribute; 47, argument_list; 48, identifier:k; 49, subscript; 50, string; 51, string; 52, identifier:format; 53, subscript; 54, call; 55, identifier:k; 56, integer:0; 57, string_content:name; 58, string_content; 59, identifier:contents; 60, string; 61, attribute; 62, argument_list; 63, escape_sequence:\n; 64, string_content:name; 65, identifier:contents; 66, identifier:get; 67, string; 68, string; 69, string_content:short_description; 70, string_content:No description | 0, 1; 1, 2; 1, 3; 1, 4; 4, 5; 4, 6; 4, 7; 4, 8; 4, 9; 5, 10; 6, 11; 7, 12; 8, 13; 8, 14; 8, 15; 9, 16; 11, 17; 11, 18; 12, 19; 12, 20; 13, 21; 13, 22; 13, 23; 14, 24; 14, 25; 15, 26; 18, 27; 20, 28; 20, 29; 25, 30; 25, 31; 26, 32; 27, 33; 27, 34; 27, 35; 28, 36; 28, 37; 31, 38; 31, 39; 32, 40; 32, 41; 36, 42; 36, 43; 39, 44; 39, 45; 41, 46; 41, 47; 44, 48; 45, 49; 45, 50; 46, 51; 46, 52; 47, 53; 47, 54; 49, 55; 49, 56; 50, 57; 51, 58; 53, 59; 53, 60; 54, 61; 54, 62; 58, 63; 60, 64; 61, 65; 61, 66; 62, 67; 62, 68; 67, 69; 68, 70 | def generate_help():
"""Generates help text with alphabetically sorted recipes."""
help_text = '\nAvailable recipes:\n\n'
recipes = config.Config.get_registered_recipes()
for contents, _, _ in sorted(recipes, key=lambda k: k[0]['name']):
help_text += ' {0:<35s}{1:s}\n'.format(
contents['name'], contents.get('short_description', 'No description'))
return help_text |
0, module; 1, function_definition; 2, function_name:write_to_csv; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, dictionary_splat_pattern; 12, expression_statement; 13, import_statement; 14, if_statement; 15, expression_statement; 16, comment:# check files before starting to write; 17, import_statement; 18, for_statement; 19, expression_statement; 20, import_from_statement; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, with_statement; 25, if_statement; 26, identifier:filename; 27, None; 28, identifier:extension; 29, string; 30, identifier:overwrite; 31, False; 32, identifier:stride; 33, integer:1; 34, identifier:chunksize; 35, None; 36, identifier:kw; 37, comment:""" write all data to csv with numpy.savetxt
Parameters
----------
filename : str, optional
filename string, which may contain placeholders {itraj} and {stride}:
* itraj will be replaced by trajetory index
* stride is stride argument of this method
If filename is not given, it is being tried to obtain the filenames
from the data source of this iterator.
extension : str, optional, default='.dat'
filename extension of created files
overwrite : bool, optional, default=False
shall existing files be overwritten? If a file exists, this method will raise.
stride : int
omit every n'th frame
chunksize: int, default=None
how many frames to process at once
kw : dict, optional
named arguments passed into numpy.savetxt (header, seperator etc.)
Example
-------
Assume you want to save features calculated by some FeatureReader to ASCII:
>>> import numpy as np, pyemma
>>> import os
>>> from pyemma.util.files import TemporaryDirectory
>>> from pyemma.util.contexts import settings
>>> data = [np.random.random((10,3))] * 3
>>> reader = pyemma.coordinates.source(data)
>>> filename = "distances_{itraj}.dat"
>>> with TemporaryDirectory() as td, settings(show_progress_bars=False):
... out = os.path.join(td, filename)
... reader.write_to_csv(out, header='', delimiter=';')
... print(sorted(os.listdir(td)))
['distances_0.dat', 'distances_1.dat', 'distances_2.dat']
"""; 38, dotted_name; 39, not_operator; 40, block; 41, elif_clause; 42, else_clause; 43, call; 44, dotted_name; 45, identifier:f; 46, identifier:filenames; 47, block; 48, assignment; 49, dotted_name; 50, dotted_name; 51, assignment; 52, assignment; 53, call; 54, with_clause; 55, block; 56, comparison_operator:f is not None; 57, block; 58, string_content:.dat; 59, identifier:os; 60, identifier:filename; 61, assert_statement; 62, comment:# raise RuntimeError("could not determine filenames"); 63, expression_statement; 64, for_statement; 65, call; 66, block; 67, block; 68, attribute; 69, argument_list; 70, identifier:errno; 71, try_statement; 72, identifier:f; 73, None; 74, identifier:pyemma; 75, identifier:_base; 76, identifier:progress; 77, identifier:ProgressReporter; 78, identifier:pg; 79, call; 80, identifier:it; 81, call; 82, attribute; 83, argument_list; 84, with_item; 85, with_item; 86, expression_statement; 87, for_statement; 88, identifier:f; 89, None; 90, expression_statement; 91, call; 92, assignment; 93, identifier:f; 94, attribute; 95, block; 96, identifier:isinstance; 97, argument_list; 98, expression_statement; 99, expression_statement; 100, raise_statement; 101, attribute; 102, identifier:debug; 103, binary_operator:"write_to_csv, filenames=%s" % filenames; 104, block; 105, except_clause; 106, identifier:ProgressReporter; 107, argument_list; 108, attribute; 109, argument_list; 110, identifier:pg; 111, identifier:register; 112, attribute; 113, string:"saving to csv"; 114, identifier:it; 115, call; 116, assignment; 117, identifier:X; 118, identifier:it; 119, block; 120, call; 121, identifier:hasattr; 122, argument_list; 123, identifier:filenames; 124, list; 125, identifier:self; 126, identifier:filenames; 127, expression_statement; 128, expression_statement; 129, identifier:filename; 130, identifier:str; 131, assignment; 132, assignment; 133, call; 134, identifier:self; 135, identifier:logger; 136, string:"write_to_csv, filenames=%s"; 137, identifier:filenames; 138, expression_statement; 139, raise_statement; 140, as_pattern; 141, block; 142, identifier:self; 143, identifier:iterator; 144, identifier:stride; 145, keyword_argument; 146, keyword_argument; 147, identifier:it; 148, identifier:n_chunks; 149, attribute; 150, argument_list; 151, identifier:oldtraj; 152, unary_operator; 153, if_statement; 154, expression_statement; 155, expression_statement; 156, expression_statement; 157, attribute; 158, argument_list; 159, identifier:self; 160, string; 161, assignment; 162, call; 163, identifier:filename; 164, call; 165, identifier:filenames; 166, list_comprehension; 167, identifier:TypeError; 168, argument_list; 169, assignment; 170, call; 171, identifier:OSError; 172, as_pattern_target; 173, if_statement; 174, raise_statement; 175, identifier:chunk; 176, identifier:chunksize; 177, identifier:return_trajindex; 178, False; 179, identifier:pg; 180, identifier:context; 181, integer:1; 182, comparison_operator:oldtraj != it.current_trajindex; 183, block; 184, call; 185, call; 186, call; 187, identifier:f; 188, identifier:close; 189, string_content:filenames; 190, pattern_list; 191, call; 192, attribute; 193, argument_list; 194, attribute; 195, argument_list; 196, call; 197, for_in_clause; 198, string:"filename should be str or None"; 199, identifier:st; 200, call; 201, identifier:OSError; 202, argument_list; 203, identifier:e; 204, comparison_operator:e.errno == errno.EEXIST; 205, block; 206, elif_clause; 207, identifier:oldtraj; 208, attribute; 209, if_statement; 210, expression_statement; 211, expression_statement; 212, expression_statement; 213, expression_statement; 214, attribute; 215, argument_list; 216, attribute; 217, argument_list; 218, attribute; 219, argument_list; 220, identifier:base; 221, identifier:_; 222, attribute; 223, argument_list; 224, identifier:filenames; 225, identifier:append; 226, binary_operator:base + extension; 227, identifier:filename; 228, identifier:replace; 229, string; 230, call; 231, attribute; 232, argument_list; 233, identifier:itraj; 234, call; 235, attribute; 236, argument_list; 237, attribute; 238, attribute; 239, attribute; 240, if_statement; 241, comparison_operator:e.errno == errno.ENOENT; 242, block; 243, identifier:it; 244, identifier:current_trajindex; 245, comparison_operator:f is not None; 246, block; 247, assignment; 248, call; 249, assignment; 250, assignment; 251, identifier:np; 252, identifier:savetxt; 253, identifier:f; 254, identifier:X; 255, dictionary_splat; 256, identifier:f; 257, identifier:flush; 258, identifier:pg; 259, identifier:update; 260, integer:1; 261, integer:0; 262, attribute; 263, identifier:splitext; 264, identifier:f; 265, identifier:base; 266, identifier:extension; 267, string_content:{stride}; 268, identifier:str; 269, argument_list; 270, identifier:filename; 271, identifier:replace; 272, string; 273, call; 274, identifier:range; 275, argument_list; 276, identifier:os; 277, identifier:stat; 278, identifier:f; 279, identifier:errno; 280, identifier:EEXIST; 281, identifier:e; 282, identifier:errno; 283, identifier:errno; 284, identifier:EEXIST; 285, identifier:overwrite; 286, block; 287, attribute; 288, attribute; 289, continue_statement; 290, identifier:f; 291, None; 292, expression_statement; 293, identifier:fn; 294, subscript; 295, attribute; 296, argument_list; 297, identifier:f; 298, call; 299, identifier:oldtraj; 300, attribute; 301, identifier:kw; 302, identifier:os; 303, identifier:path; 304, identifier:stride; 305, string_content:{itraj}; 306, identifier:str; 307, argument_list; 308, call; 309, continue_statement; 310, identifier:e; 311, identifier:errno; 312, identifier:errno; 313, identifier:ENOENT; 314, call; 315, identifier:filenames; 316, attribute; 317, attribute; 318, identifier:debug; 319, binary_operator:"opening file %s for writing csv." % fn; 320, identifier:open; 321, argument_list; 322, identifier:it; 323, identifier:current_trajindex; 324, identifier:itraj; 325, attribute; 326, argument_list; 327, attribute; 328, argument_list; 329, identifier:it; 330, identifier:current_trajindex; 331, identifier:self; 332, identifier:logger; 333, string:"opening file %s for writing csv."; 334, identifier:fn; 335, identifier:fn; 336, string; 337, identifier:self; 338, identifier:number_of_trajectories; 339, identifier:f; 340, identifier:close; 341, string_content:wb | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 6, 26; 6, 27; 7, 28; 7, 29; 8, 30; 8, 31; 9, 32; 9, 33; 10, 34; 10, 35; 11, 36; 12, 37; 13, 38; 14, 39; 14, 40; 14, 41; 14, 42; 15, 43; 17, 44; 18, 45; 18, 46; 18, 47; 19, 48; 20, 49; 20, 50; 21, 51; 22, 52; 23, 53; 24, 54; 24, 55; 25, 56; 25, 57; 29, 58; 38, 59; 39, 60; 40, 61; 40, 62; 40, 63; 40, 64; 41, 65; 41, 66; 42, 67; 43, 68; 43, 69; 44, 70; 47, 71; 48, 72; 48, 73; 49, 74; 49, 75; 49, 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; 61, 91; 63, 92; 64, 93; 64, 94; 64, 95; 65, 96; 65, 97; 66, 98; 66, 99; 67, 100; 68, 101; 68, 102; 69, 103; 71, 104; 71, 105; 79, 106; 79, 107; 81, 108; 81, 109; 82, 110; 82, 111; 83, 112; 83, 113; 84, 114; 85, 115; 86, 116; 87, 117; 87, 118; 87, 119; 90, 120; 91, 121; 91, 122; 92, 123; 92, 124; 94, 125; 94, 126; 95, 127; 95, 128; 97, 129; 97, 130; 98, 131; 99, 132; 100, 133; 101, 134; 101, 135; 103, 136; 103, 137; 104, 138; 104, 139; 105, 140; 105, 141; 108, 142; 108, 143; 109, 144; 109, 145; 109, 146; 112, 147; 112, 148; 115, 149; 115, 150; 116, 151; 116, 152; 119, 153; 119, 154; 119, 155; 119, 156; 120, 157; 120, 158; 122, 159; 122, 160; 127, 161; 128, 162; 131, 163; 131, 164; 132, 165; 132, 166; 133, 167; 133, 168; 138, 169; 139, 170; 140, 171; 140, 172; 141, 173; 141, 174; 145, 175; 145, 176; 146, 177; 146, 178; 149, 179; 149, 180; 152, 181; 153, 182; 153, 183; 154, 184; 155, 185; 156, 186; 157, 187; 157, 188; 160, 189; 161, 190; 161, 191; 162, 192; 162, 193; 164, 194; 164, 195; 166, 196; 166, 197; 168, 198; 169, 199; 169, 200; 170, 201; 170, 202; 172, 203; 173, 204; 173, 205; 173, 206; 182, 207; 182, 208; 183, 209; 183, 210; 183, 211; 183, 212; 183, 213; 184, 214; 184, 215; 185, 216; 185, 217; 186, 218; 186, 219; 190, 220; 190, 221; 191, 222; 191, 223; 192, 224; 192, 225; 193, 226; 194, 227; 194, 228; 195, 229; 195, 230; 196, 231; 196, 232; 197, 233; 197, 234; 200, 235; 200, 236; 202, 237; 204, 238; 204, 239; 205, 240; 206, 241; 206, 242; 208, 243; 208, 244; 209, 245; 209, 246; 210, 247; 211, 248; 212, 249; 213, 250; 214, 251; 214, 252; 215, 253; 215, 254; 215, 255; 216, 256; 216, 257; 218, 258; 218, 259; 219, 260; 219, 261; 222, 262; 222, 263; 223, 264; 226, 265; 226, 266; 229, 267; 230, 268; 230, 269; 231, 270; 231, 271; 232, 272; 232, 273; 234, 274; 234, 275; 235, 276; 235, 277; 236, 278; 237, 279; 237, 280; 238, 281; 238, 282; 239, 283; 239, 284; 240, 285; 240, 286; 241, 287; 241, 288; 242, 289; 245, 290; 245, 291; 246, 292; 247, 293; 247, 294; 248, 295; 248, 296; 249, 297; 249, 298; 250, 299; 250, 300; 255, 301; 262, 302; 262, 303; 269, 304; 272, 305; 273, 306; 273, 307; 275, 308; 286, 309; 287, 310; 287, 311; 288, 312; 288, 313; 292, 314; 294, 315; 294, 316; 295, 317; 295, 318; 296, 319; 298, 320; 298, 321; 300, 322; 300, 323; 307, 324; 308, 325; 308, 326; 314, 327; 314, 328; 316, 329; 316, 330; 317, 331; 317, 332; 319, 333; 319, 334; 321, 335; 321, 336; 325, 337; 325, 338; 327, 339; 327, 340; 336, 341 | def write_to_csv(self, filename=None, extension='.dat', overwrite=False,
stride=1, chunksize=None, **kw):
""" write all data to csv with numpy.savetxt
Parameters
----------
filename : str, optional
filename string, which may contain placeholders {itraj} and {stride}:
* itraj will be replaced by trajetory index
* stride is stride argument of this method
If filename is not given, it is being tried to obtain the filenames
from the data source of this iterator.
extension : str, optional, default='.dat'
filename extension of created files
overwrite : bool, optional, default=False
shall existing files be overwritten? If a file exists, this method will raise.
stride : int
omit every n'th frame
chunksize: int, default=None
how many frames to process at once
kw : dict, optional
named arguments passed into numpy.savetxt (header, seperator etc.)
Example
-------
Assume you want to save features calculated by some FeatureReader to ASCII:
>>> import numpy as np, pyemma
>>> import os
>>> from pyemma.util.files import TemporaryDirectory
>>> from pyemma.util.contexts import settings
>>> data = [np.random.random((10,3))] * 3
>>> reader = pyemma.coordinates.source(data)
>>> filename = "distances_{itraj}.dat"
>>> with TemporaryDirectory() as td, settings(show_progress_bars=False):
... out = os.path.join(td, filename)
... reader.write_to_csv(out, header='', delimiter=';')
... print(sorted(os.listdir(td)))
['distances_0.dat', 'distances_1.dat', 'distances_2.dat']
"""
import os
if not filename:
assert hasattr(self, 'filenames')
# raise RuntimeError("could not determine filenames")
filenames = []
for f in self.filenames:
base, _ = os.path.splitext(f)
filenames.append(base + extension)
elif isinstance(filename, str):
filename = filename.replace('{stride}', str(stride))
filenames = [filename.replace('{itraj}', str(itraj)) for itraj
in range(self.number_of_trajectories())]
else:
raise TypeError("filename should be str or None")
self.logger.debug("write_to_csv, filenames=%s" % filenames)
# check files before starting to write
import errno
for f in filenames:
try:
st = os.stat(f)
raise OSError(errno.EEXIST)
except OSError as e:
if e.errno == errno.EEXIST:
if overwrite:
continue
elif e.errno == errno.ENOENT:
continue
raise
f = None
from pyemma._base.progress import ProgressReporter
pg = ProgressReporter()
it = self.iterator(stride, chunk=chunksize, return_trajindex=False)
pg.register(it.n_chunks, "saving to csv")
with it, pg.context():
oldtraj = -1
for X in it:
if oldtraj != it.current_trajindex:
if f is not None:
f.close()
fn = filenames[it.current_trajindex]
self.logger.debug("opening file %s for writing csv." % fn)
f = open(fn, 'wb')
oldtraj = it.current_trajindex
np.savetxt(f, X, **kw)
f.flush()
pg.update(1, 0)
if f is not None:
f.close() |
0, module; 1, function_definition; 2, function_name:add_distances; 3, parameters; 4, block; 5, identifier:self; 6, identifier:indices; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, import_from_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, identifier:periodic; 16, True; 17, identifier:indices2; 18, None; 19, comment:r"""
Adds the distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the iterable of integers input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""; 20, relative_import; 21, dotted_name; 22, assignment; 23, assignment; 24, assignment; 25, call; 26, import_prefix; 27, dotted_name; 28, identifier:DistanceFeature; 29, identifier:atom_pairs; 30, call; 31, identifier:atom_pairs; 32, call; 33, identifier:f; 34, call; 35, attribute; 36, argument_list; 37, identifier:distances; 38, identifier:_parse_pairwise_input; 39, argument_list; 40, attribute; 41, argument_list; 42, identifier:DistanceFeature; 43, argument_list; 44, identifier:self; 45, identifier:__add_feature; 46, identifier:f; 47, identifier:indices; 48, identifier:indices2; 49, attribute; 50, keyword_argument; 51, identifier:self; 52, identifier:_check_indices; 53, identifier:atom_pairs; 54, attribute; 55, identifier:atom_pairs; 56, keyword_argument; 57, identifier:self; 58, identifier:logger; 59, identifier:fname; 60, string; 61, identifier:self; 62, identifier:topology; 63, identifier:periodic; 64, identifier:periodic; 65, string_content:add_distances() | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 7, 15; 7, 16; 8, 17; 8, 18; 9, 19; 10, 20; 10, 21; 11, 22; 12, 23; 13, 24; 14, 25; 20, 26; 20, 27; 21, 28; 22, 29; 22, 30; 23, 31; 23, 32; 24, 33; 24, 34; 25, 35; 25, 36; 27, 37; 30, 38; 30, 39; 32, 40; 32, 41; 34, 42; 34, 43; 35, 44; 35, 45; 36, 46; 39, 47; 39, 48; 39, 49; 39, 50; 40, 51; 40, 52; 41, 53; 43, 54; 43, 55; 43, 56; 49, 57; 49, 58; 50, 59; 50, 60; 54, 61; 54, 62; 56, 63; 56, 64; 60, 65 | def add_distances(self, indices, periodic=True, indices2=None):
r"""
Adds the distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the iterable of integers input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import DistanceFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_distances()')
atom_pairs = self._check_indices(atom_pairs)
f = DistanceFeature(self.topology, atom_pairs, periodic=periodic)
self.__add_feature(f) |
0, module; 1, function_definition; 2, function_name:add_inverse_distances; 3, parameters; 4, block; 5, identifier:self; 6, identifier:indices; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, import_from_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, identifier:periodic; 16, True; 17, identifier:indices2; 18, None; 19, comment:"""
Adds the inverse distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the inverse distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the inverse distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the inverse distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""; 20, relative_import; 21, dotted_name; 22, assignment; 23, assignment; 24, assignment; 25, call; 26, import_prefix; 27, dotted_name; 28, identifier:InverseDistanceFeature; 29, identifier:atom_pairs; 30, call; 31, identifier:atom_pairs; 32, call; 33, identifier:f; 34, call; 35, attribute; 36, argument_list; 37, identifier:distances; 38, identifier:_parse_pairwise_input; 39, argument_list; 40, attribute; 41, argument_list; 42, identifier:InverseDistanceFeature; 43, argument_list; 44, identifier:self; 45, identifier:__add_feature; 46, identifier:f; 47, identifier:indices; 48, identifier:indices2; 49, attribute; 50, keyword_argument; 51, identifier:self; 52, identifier:_check_indices; 53, identifier:atom_pairs; 54, attribute; 55, identifier:atom_pairs; 56, keyword_argument; 57, identifier:self; 58, identifier:logger; 59, identifier:fname; 60, string; 61, identifier:self; 62, identifier:topology; 63, identifier:periodic; 64, identifier:periodic; 65, string_content:add_inverse_distances() | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 7, 15; 7, 16; 8, 17; 8, 18; 9, 19; 10, 20; 10, 21; 11, 22; 12, 23; 13, 24; 14, 25; 20, 26; 20, 27; 21, 28; 22, 29; 22, 30; 23, 31; 23, 32; 24, 33; 24, 34; 25, 35; 25, 36; 27, 37; 30, 38; 30, 39; 32, 40; 32, 41; 34, 42; 34, 43; 35, 44; 35, 45; 36, 46; 39, 47; 39, 48; 39, 49; 39, 50; 40, 51; 40, 52; 41, 53; 43, 54; 43, 55; 43, 56; 49, 57; 49, 58; 50, 59; 50, 60; 54, 61; 54, 62; 56, 63; 56, 64; 60, 65 | def add_inverse_distances(self, indices, periodic=True, indices2=None):
"""
Adds the inverse distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the inverse distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the inverse distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the inverse distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import InverseDistanceFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_inverse_distances()')
atom_pairs = self._check_indices(atom_pairs)
f = InverseDistanceFeature(self.topology, atom_pairs, periodic=periodic)
self.__add_feature(f) |
0, module; 1, function_definition; 2, function_name:add_contacts; 3, parameters; 4, block; 5, identifier:self; 6, identifier:indices; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, import_from_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, identifier:indices2; 18, None; 19, identifier:threshold; 20, float:0.3; 21, identifier:periodic; 22, True; 23, identifier:count_contacts; 24, False; 25, comment:r"""
Adds the contacts to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the contacts shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the contacts shall be computed.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the contacts between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
threshold : float, optional, default = .3
distances below this threshold (in nm) will result in a feature 1.0, distances above will result in 0.0.
The default is set to .3 nm (3 Angstrom)
periodic : boolean, default True
use the minimum image convention if unitcell information is available
count_contacts : boolean, default False
If set to true, this feature will return the number of formed contacts (and not feature values with either 1.0 or 0)
The ouput of this feature will be of shape (Nt,1), and not (Nt, nr_of_contacts)
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""; 26, relative_import; 27, dotted_name; 28, assignment; 29, assignment; 30, assignment; 31, call; 32, import_prefix; 33, dotted_name; 34, identifier:ContactFeature; 35, identifier:atom_pairs; 36, call; 37, identifier:atom_pairs; 38, call; 39, identifier:f; 40, call; 41, attribute; 42, argument_list; 43, identifier:distances; 44, identifier:_parse_pairwise_input; 45, argument_list; 46, attribute; 47, argument_list; 48, identifier:ContactFeature; 49, argument_list; 50, identifier:self; 51, identifier:__add_feature; 52, identifier:f; 53, identifier:indices; 54, identifier:indices2; 55, attribute; 56, keyword_argument; 57, identifier:self; 58, identifier:_check_indices; 59, identifier:atom_pairs; 60, attribute; 61, identifier:atom_pairs; 62, identifier:threshold; 63, identifier:periodic; 64, identifier:count_contacts; 65, identifier:self; 66, identifier:logger; 67, identifier:fname; 68, string; 69, identifier:self; 70, identifier:topology; 71, string_content:add_contacts() | 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; 7, 17; 7, 18; 8, 19; 8, 20; 9, 21; 9, 22; 10, 23; 10, 24; 11, 25; 12, 26; 12, 27; 13, 28; 14, 29; 15, 30; 16, 31; 26, 32; 26, 33; 27, 34; 28, 35; 28, 36; 29, 37; 29, 38; 30, 39; 30, 40; 31, 41; 31, 42; 33, 43; 36, 44; 36, 45; 38, 46; 38, 47; 40, 48; 40, 49; 41, 50; 41, 51; 42, 52; 45, 53; 45, 54; 45, 55; 45, 56; 46, 57; 46, 58; 47, 59; 49, 60; 49, 61; 49, 62; 49, 63; 49, 64; 55, 65; 55, 66; 56, 67; 56, 68; 60, 69; 60, 70; 68, 71 | def add_contacts(self, indices, indices2=None, threshold=0.3, periodic=True, count_contacts=False):
r"""
Adds the contacts to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the contacts shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the contacts shall be computed.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the contacts between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
threshold : float, optional, default = .3
distances below this threshold (in nm) will result in a feature 1.0, distances above will result in 0.0.
The default is set to .3 nm (3 Angstrom)
periodic : boolean, default True
use the minimum image convention if unitcell information is available
count_contacts : boolean, default False
If set to true, this feature will return the number of formed contacts (and not feature values with either 1.0 or 0)
The ouput of this feature will be of shape (Nt,1), and not (Nt, nr_of_contacts)
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import ContactFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_contacts()')
atom_pairs = self._check_indices(atom_pairs)
f = ContactFeature(self.topology, atom_pairs, threshold, periodic, count_contacts)
self.__add_feature(f) |
0, module; 1, function_definition; 2, function_name:spd_eig; 3, parameters; 4, block; 5, identifier:W; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, comment:# check input; 11, assert_statement; 12, if_statement; 13, expression_statement; 14, comment:# sort them; 15, comment:# determine the cutoff. We know that C0 is an spd matrix,; 16, comment:# so we select the truncation threshold such that everything that is negative vanishes; 17, expression_statement; 18, if_statement; 19, comment:# determine effective rank m and perform low-rank approximations.; 20, expression_statement; 21, expression_statement; 22, expression_statement; 23, if_statement; 24, expression_statement; 25, expression_statement; 26, if_statement; 27, return_statement; 28, identifier:epsilon; 29, float:1e-10; 30, identifier:method; 31, string; 32, identifier:canonical_signs; 33, False; 34, comment:""" Rank-reduced eigenvalue decomposition of symmetric positive definite matrix.
Removes all negligible eigenvalues
Parameters
----------
W : ndarray((n, n), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than this cutoff will
be removed.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
canonical_signs : boolean, default = False
Fix signs in V, s. t. the largest element of in every row of V is positive.
Returns
-------
s : ndarray(k)
k non-negligible eigenvalues, sorted by descending norms
V : ndarray(n, k)
k leading eigenvectors
"""; 35, call; 36, string; 37, comparison_operator:method.lower() == 'qr'; 38, block; 39, comment:# compute the Eigenvalues of C0 using Schur factorization; 40, elif_clause; 41, else_clause; 42, assignment; 43, assignment; 44, comparison_operator:evmin < 0; 45, block; 46, assignment; 47, assignment; 48, assignment; 49, comparison_operator:m == 0; 50, block; 51, assignment; 52, assignment; 53, identifier:canonical_signs; 54, comment:# enforce canonical eigenvector signs; 55, block; 56, expression_list; 57, string_content:QR; 58, attribute; 59, argument_list; 60, string_content:W is not a symmetric matrix; 61, call; 62, string; 63, import_from_statement; 64, expression_statement; 65, comparison_operator:method.lower() == 'schur'; 66, block; 67, block; 68, pattern_list; 69, call; 70, identifier:evmin; 71, call; 72, identifier:evmin; 73, integer:0; 74, expression_statement; 75, identifier:evnorms; 76, call; 77, identifier:n; 78, subscript; 79, identifier:m; 80, binary_operator:n - _np.searchsorted(evnorms[::-1], epsilon); 81, identifier:m; 82, integer:0; 83, raise_statement; 84, identifier:Vm; 85, subscript; 86, identifier:sm; 87, subscript; 88, for_statement; 89, identifier:sm; 90, identifier:Vm; 91, identifier:_np; 92, identifier:allclose; 93, attribute; 94, identifier:W; 95, attribute; 96, argument_list; 97, string_content:qr; 98, relative_import; 99, dotted_name; 100, assignment; 101, call; 102, string; 103, import_from_statement; 104, expression_statement; 105, expression_statement; 106, raise_statement; 107, identifier:s; 108, identifier:V; 109, identifier:sort_by_norm; 110, argument_list; 111, attribute; 112, argument_list; 113, assignment; 114, attribute; 115, argument_list; 116, call; 117, integer:0; 118, identifier:n; 119, call; 120, call; 121, identifier:V; 122, slice; 123, slice; 124, identifier:s; 125, slice; 126, identifier:j; 127, call; 128, block; 129, identifier:W; 130, identifier:T; 131, identifier:method; 132, identifier:lower; 133, import_prefix; 134, dotted_name; 135, identifier:eig_qr; 136, pattern_list; 137, call; 138, attribute; 139, argument_list; 140, string_content:schur; 141, dotted_name; 142, dotted_name; 143, assignment; 144, assignment; 145, call; 146, identifier:s; 147, identifier:V; 148, identifier:_np; 149, identifier:min; 150, identifier:s; 151, identifier:epsilon; 152, call; 153, identifier:_np; 154, identifier:abs; 155, identifier:s; 156, attribute; 157, argument_list; 158, attribute; 159, argument_list; 160, identifier:_ZeroRankError; 161, argument_list; 162, integer:0; 163, identifier:m; 164, integer:0; 165, identifier:m; 166, identifier:range; 167, argument_list; 168, expression_statement; 169, expression_statement; 170, identifier:eig_qr; 171, identifier:eig_qr; 172, identifier:s; 173, identifier:V; 174, identifier:eig_qr; 175, argument_list; 176, identifier:method; 177, identifier:lower; 178, identifier:scipy; 179, identifier:linalg; 180, identifier:schur; 181, pattern_list; 182, call; 183, identifier:s; 184, call; 185, identifier:ValueError; 186, argument_list; 187, identifier:max; 188, argument_list; 189, identifier:_np; 190, identifier:shape; 191, identifier:evnorms; 192, identifier:_np; 193, identifier:searchsorted; 194, subscript; 195, identifier:epsilon; 196, binary_operator:'All eigenvalues are smaller than %g, rank reduction would discard all dimensions.'%epsilon; 197, identifier:m; 198, assignment; 199, augmented_assignment; 200, identifier:W; 201, identifier:S; 202, identifier:V; 203, identifier:schur; 204, argument_list; 205, attribute; 206, argument_list; 207, binary_operator:'method not implemented: ' + method; 208, identifier:epsilon; 209, binary_operator:-evmin + 1e-16; 210, identifier:evnorms; 211, slice; 212, string; 213, identifier:epsilon; 214, identifier:jj; 215, call; 216, subscript; 217, call; 218, identifier:W; 219, identifier:_np; 220, identifier:diag; 221, identifier:S; 222, string; 223, identifier:method; 224, unary_operator; 225, float:1e-16; 226, unary_operator; 227, string_content:All eigenvalues are smaller than %g, rank reduction would discard all dimensions.; 228, attribute; 229, argument_list; 230, identifier:Vm; 231, slice; 232, identifier:j; 233, attribute; 234, argument_list; 235, string_content:method not implemented:; 236, identifier:evmin; 237, integer:1; 238, identifier:_np; 239, identifier:argmax; 240, call; 241, identifier:_np; 242, identifier:sign; 243, subscript; 244, attribute; 245, argument_list; 246, identifier:Vm; 247, identifier:jj; 248, identifier:j; 249, identifier:_np; 250, identifier:abs; 251, subscript; 252, identifier:Vm; 253, slice; 254, identifier:j | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 6, 28; 6, 29; 7, 30; 7, 31; 8, 32; 8, 33; 9, 34; 11, 35; 11, 36; 12, 37; 12, 38; 12, 39; 12, 40; 12, 41; 13, 42; 17, 43; 18, 44; 18, 45; 20, 46; 21, 47; 22, 48; 23, 49; 23, 50; 24, 51; 25, 52; 26, 53; 26, 54; 26, 55; 27, 56; 31, 57; 35, 58; 35, 59; 36, 60; 37, 61; 37, 62; 38, 63; 38, 64; 40, 65; 40, 66; 41, 67; 42, 68; 42, 69; 43, 70; 43, 71; 44, 72; 44, 73; 45, 74; 46, 75; 46, 76; 47, 77; 47, 78; 48, 79; 48, 80; 49, 81; 49, 82; 50, 83; 51, 84; 51, 85; 52, 86; 52, 87; 55, 88; 56, 89; 56, 90; 58, 91; 58, 92; 59, 93; 59, 94; 61, 95; 61, 96; 62, 97; 63, 98; 63, 99; 64, 100; 65, 101; 65, 102; 66, 103; 66, 104; 66, 105; 67, 106; 68, 107; 68, 108; 69, 109; 69, 110; 71, 111; 71, 112; 74, 113; 76, 114; 76, 115; 78, 116; 78, 117; 80, 118; 80, 119; 83, 120; 85, 121; 85, 122; 85, 123; 87, 124; 87, 125; 88, 126; 88, 127; 88, 128; 93, 129; 93, 130; 95, 131; 95, 132; 98, 133; 98, 134; 99, 135; 100, 136; 100, 137; 101, 138; 101, 139; 102, 140; 103, 141; 103, 142; 104, 143; 105, 144; 106, 145; 110, 146; 110, 147; 111, 148; 111, 149; 112, 150; 113, 151; 113, 152; 114, 153; 114, 154; 115, 155; 116, 156; 116, 157; 119, 158; 119, 159; 120, 160; 120, 161; 123, 162; 123, 163; 125, 164; 125, 165; 127, 166; 127, 167; 128, 168; 128, 169; 134, 170; 134, 171; 136, 172; 136, 173; 137, 174; 137, 175; 138, 176; 138, 177; 141, 178; 141, 179; 142, 180; 143, 181; 143, 182; 144, 183; 144, 184; 145, 185; 145, 186; 152, 187; 152, 188; 156, 189; 156, 190; 157, 191; 158, 192; 158, 193; 159, 194; 159, 195; 161, 196; 167, 197; 168, 198; 169, 199; 175, 200; 181, 201; 181, 202; 182, 203; 182, 204; 184, 205; 184, 206; 186, 207; 188, 208; 188, 209; 194, 210; 194, 211; 196, 212; 196, 213; 198, 214; 198, 215; 199, 216; 199, 217; 204, 218; 205, 219; 205, 220; 206, 221; 207, 222; 207, 223; 209, 224; 209, 225; 211, 226; 212, 227; 215, 228; 215, 229; 216, 230; 216, 231; 216, 232; 217, 233; 217, 234; 222, 235; 224, 236; 226, 237; 228, 238; 228, 239; 229, 240; 233, 241; 233, 242; 234, 243; 240, 244; 240, 245; 243, 246; 243, 247; 243, 248; 244, 249; 244, 250; 245, 251; 251, 252; 251, 253; 251, 254 | def spd_eig(W, epsilon=1e-10, method='QR', canonical_signs=False):
""" Rank-reduced eigenvalue decomposition of symmetric positive definite matrix.
Removes all negligible eigenvalues
Parameters
----------
W : ndarray((n, n), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than this cutoff will
be removed.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
canonical_signs : boolean, default = False
Fix signs in V, s. t. the largest element of in every row of V is positive.
Returns
-------
s : ndarray(k)
k non-negligible eigenvalues, sorted by descending norms
V : ndarray(n, k)
k leading eigenvectors
"""
# check input
assert _np.allclose(W.T, W), 'W is not a symmetric matrix'
if method.lower() == 'qr':
from .eig_qr.eig_qr import eig_qr
s, V = eig_qr(W)
# compute the Eigenvalues of C0 using Schur factorization
elif method.lower() == 'schur':
from scipy.linalg import schur
S, V = schur(W)
s = _np.diag(S)
else:
raise ValueError('method not implemented: ' + method)
s, V = sort_by_norm(s, V) # sort them
# determine the cutoff. We know that C0 is an spd matrix,
# so we select the truncation threshold such that everything that is negative vanishes
evmin = _np.min(s)
if evmin < 0:
epsilon = max(epsilon, -evmin + 1e-16)
# determine effective rank m and perform low-rank approximations.
evnorms = _np.abs(s)
n = _np.shape(evnorms)[0]
m = n - _np.searchsorted(evnorms[::-1], epsilon)
if m == 0:
raise _ZeroRankError('All eigenvalues are smaller than %g, rank reduction would discard all dimensions.'%epsilon)
Vm = V[:, 0:m]
sm = s[0:m]
if canonical_signs:
# enforce canonical eigenvector signs
for j in range(m):
jj = _np.argmax(_np.abs(Vm[:, j]))
Vm[:, j] *= _np.sign(Vm[jj, j])
return sm, Vm |
0, module; 1, function_definition; 2, function_name:eig_corr; 3, parameters; 4, block; 5, identifier:C0; 6, identifier:Ct; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, comment:# solve the symmetric eigenvalue problem in the new basis; 14, if_statement; 15, comment:# sort eigenpairs; 16, expression_statement; 17, comment:# transform the eigenvectors back to the old basis; 18, expression_statement; 19, comment:# Change signs of eigenvectors:; 20, if_statement; 21, comment:# return result; 22, return_statement; 23, identifier:epsilon; 24, float:1e-10; 25, identifier:method; 26, string; 27, identifier:sign_maxelement; 28, False; 29, comment:r""" Solve generalized eigenvalue problem with correlation matrices C0 and Ct
Numerically robust solution of a generalized Hermitian (symmetric) eigenvalue
problem of the form
.. math::
\mathbf{C}_t \mathbf{r}_i = \mathbf{C}_0 \mathbf{r}_i l_i
Computes :math:`m` dominant eigenvalues :math:`l_i` and eigenvectors
:math:`\mathbf{r}_i`, where :math:`m` is the numerical rank of the problem.
This is done by first conducting a Schur decomposition of the symmetric
positive matrix :math:`\mathbf{C}_0`, then truncating its spectrum to
retain only eigenvalues that are numerically greater than zero, then using
this decomposition to define an ordinary eigenvalue Problem for
:math:`\mathbf{C}_t` of size :math:`m`, and then solving this eigenvalue
problem.
Parameters
----------
C0 : ndarray (n,n)
time-instantaneous correlation matrix. Must be symmetric positive definite
Ct : ndarray (n,n)
time-lagged correlation matrix. Must be symmetric
epsilon : float
eigenvalue norm cutoff. Eigenvalues of C0 with norms <= epsilon will be
cut off. The remaining number of Eigenvalues define the size of
the output.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
sign_maxelement : bool
If True, re-scale each eigenvector such that its entry with maximal absolute value
is positive.
Returns
-------
l : ndarray (m)
The first m generalized eigenvalues, sorted by descending norm
R : ndarray (n,m)
The first m generalized eigenvectors, as a column matrix.
"""; 30, assignment; 31, assignment; 32, call; 33, block; 34, else_clause; 35, assignment; 36, assignment; 37, identifier:sign_maxelement; 38, block; 39, expression_list; 40, string_content:QR; 41, identifier:L; 42, call; 43, identifier:Ct_trans; 44, call; 45, attribute; 46, argument_list; 47, import_from_statement; 48, expression_statement; 49, block; 50, pattern_list; 51, call; 52, identifier:R; 53, call; 54, for_statement; 55, identifier:l; 56, identifier:R; 57, identifier:spd_inv_split; 58, argument_list; 59, attribute; 60, argument_list; 61, identifier:_np; 62, identifier:allclose; 63, attribute; 64, identifier:Ct; 65, dotted_name; 66, dotted_name; 67, assignment; 68, import_from_statement; 69, expression_statement; 70, identifier:l; 71, identifier:R_trans; 72, identifier:sort_by_norm; 73, argument_list; 74, attribute; 75, argument_list; 76, identifier:j; 77, call; 78, block; 79, identifier:C0; 80, keyword_argument; 81, keyword_argument; 82, keyword_argument; 83, identifier:_np; 84, identifier:dot; 85, call; 86, identifier:L; 87, identifier:Ct; 88, identifier:T; 89, identifier:scipy; 90, identifier:linalg; 91, identifier:eigh; 92, pattern_list; 93, call; 94, dotted_name; 95, dotted_name; 96, assignment; 97, identifier:l; 98, identifier:R_trans; 99, identifier:_np; 100, identifier:dot; 101, identifier:L; 102, identifier:R_trans; 103, identifier:range; 104, argument_list; 105, expression_statement; 106, expression_statement; 107, identifier:epsilon; 108, identifier:epsilon; 109, identifier:method; 110, identifier:method; 111, identifier:canonical_signs; 112, True; 113, attribute; 114, argument_list; 115, identifier:l; 116, identifier:R_trans; 117, identifier:eigh; 118, argument_list; 119, identifier:scipy; 120, identifier:linalg; 121, identifier:eig; 122, pattern_list; 123, call; 124, subscript; 125, assignment; 126, augmented_assignment; 127, identifier:_np; 128, identifier:dot; 129, attribute; 130, identifier:Ct; 131, identifier:Ct_trans; 132, identifier:l; 133, identifier:R_trans; 134, identifier:eig; 135, argument_list; 136, attribute; 137, integer:1; 138, identifier:imax; 139, call; 140, subscript; 141, call; 142, identifier:L; 143, identifier:T; 144, identifier:Ct_trans; 145, identifier:R; 146, identifier:shape; 147, attribute; 148, argument_list; 149, identifier:R; 150, slice; 151, identifier:j; 152, attribute; 153, argument_list; 154, identifier:_np; 155, identifier:argmax; 156, call; 157, identifier:_np; 158, identifier:sign; 159, subscript; 160, attribute; 161, argument_list; 162, identifier:R; 163, identifier:imax; 164, identifier:j; 165, identifier:_np; 166, identifier:abs; 167, subscript; 168, identifier:R; 169, slice; 170, identifier:j | 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; 7, 23; 7, 24; 8, 25; 8, 26; 9, 27; 9, 28; 10, 29; 11, 30; 12, 31; 14, 32; 14, 33; 14, 34; 16, 35; 18, 36; 20, 37; 20, 38; 22, 39; 26, 40; 30, 41; 30, 42; 31, 43; 31, 44; 32, 45; 32, 46; 33, 47; 33, 48; 34, 49; 35, 50; 35, 51; 36, 52; 36, 53; 38, 54; 39, 55; 39, 56; 42, 57; 42, 58; 44, 59; 44, 60; 45, 61; 45, 62; 46, 63; 46, 64; 47, 65; 47, 66; 48, 67; 49, 68; 49, 69; 50, 70; 50, 71; 51, 72; 51, 73; 53, 74; 53, 75; 54, 76; 54, 77; 54, 78; 58, 79; 58, 80; 58, 81; 58, 82; 59, 83; 59, 84; 60, 85; 60, 86; 63, 87; 63, 88; 65, 89; 65, 90; 66, 91; 67, 92; 67, 93; 68, 94; 68, 95; 69, 96; 73, 97; 73, 98; 74, 99; 74, 100; 75, 101; 75, 102; 77, 103; 77, 104; 78, 105; 78, 106; 80, 107; 80, 108; 81, 109; 81, 110; 82, 111; 82, 112; 85, 113; 85, 114; 92, 115; 92, 116; 93, 117; 93, 118; 94, 119; 94, 120; 95, 121; 96, 122; 96, 123; 104, 124; 105, 125; 106, 126; 113, 127; 113, 128; 114, 129; 114, 130; 118, 131; 122, 132; 122, 133; 123, 134; 123, 135; 124, 136; 124, 137; 125, 138; 125, 139; 126, 140; 126, 141; 129, 142; 129, 143; 135, 144; 136, 145; 136, 146; 139, 147; 139, 148; 140, 149; 140, 150; 140, 151; 141, 152; 141, 153; 147, 154; 147, 155; 148, 156; 152, 157; 152, 158; 153, 159; 156, 160; 156, 161; 159, 162; 159, 163; 159, 164; 160, 165; 160, 166; 161, 167; 167, 168; 167, 169; 167, 170 | def eig_corr(C0, Ct, epsilon=1e-10, method='QR', sign_maxelement=False):
r""" Solve generalized eigenvalue problem with correlation matrices C0 and Ct
Numerically robust solution of a generalized Hermitian (symmetric) eigenvalue
problem of the form
.. math::
\mathbf{C}_t \mathbf{r}_i = \mathbf{C}_0 \mathbf{r}_i l_i
Computes :math:`m` dominant eigenvalues :math:`l_i` and eigenvectors
:math:`\mathbf{r}_i`, where :math:`m` is the numerical rank of the problem.
This is done by first conducting a Schur decomposition of the symmetric
positive matrix :math:`\mathbf{C}_0`, then truncating its spectrum to
retain only eigenvalues that are numerically greater than zero, then using
this decomposition to define an ordinary eigenvalue Problem for
:math:`\mathbf{C}_t` of size :math:`m`, and then solving this eigenvalue
problem.
Parameters
----------
C0 : ndarray (n,n)
time-instantaneous correlation matrix. Must be symmetric positive definite
Ct : ndarray (n,n)
time-lagged correlation matrix. Must be symmetric
epsilon : float
eigenvalue norm cutoff. Eigenvalues of C0 with norms <= epsilon will be
cut off. The remaining number of Eigenvalues define the size of
the output.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
sign_maxelement : bool
If True, re-scale each eigenvector such that its entry with maximal absolute value
is positive.
Returns
-------
l : ndarray (m)
The first m generalized eigenvalues, sorted by descending norm
R : ndarray (n,m)
The first m generalized eigenvectors, as a column matrix.
"""
L = spd_inv_split(C0, epsilon=epsilon, method=method, canonical_signs=True)
Ct_trans = _np.dot(_np.dot(L.T, Ct), L)
# solve the symmetric eigenvalue problem in the new basis
if _np.allclose(Ct.T, Ct):
from scipy.linalg import eigh
l, R_trans = eigh(Ct_trans)
else:
from scipy.linalg import eig
l, R_trans = eig(Ct_trans)
# sort eigenpairs
l, R_trans = sort_by_norm(l, R_trans)
# transform the eigenvectors back to the old basis
R = _np.dot(L, R_trans)
# Change signs of eigenvectors:
if sign_maxelement:
for j in range(R.shape[1]):
imax = _np.argmax(_np.abs(R[:, j]))
R[:, j] *= _np.sign(R[imax, j])
# return result
return l, R |
0, module; 1, function_definition; 2, function_name:sortino_ratio; 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:threshold; 13, float:0.0; 14, identifier:ddof; 15, integer:0; 16, identifier:freq; 17, None; 18, comment:"""Return over a threshold per unit of downside deviation.
A performance appraisal ratio that replaces standard deviation
in the Sharpe ratio with downside deviation.
[Source: CFA Institute]
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
While zero is the default, it is also customary to use
a "minimum acceptable return" (MAR) or a risk-free rate.
Note: this is assumed to be a *periodic*, not necessarily
annualized, return.
ddof : int, default 0
Degrees of freedom, passed to pd.Series.std().
freq : str or None, default None
A frequency string used to create an annualization factor.
If None, `self.freq` will be used. If that is also None,
a frequency will be inferred. If none can be inferred,
an exception is raised.
It may be any frequency string or anchored offset string
recognized by Pandas, such as 'D', '5D', 'Q', 'Q-DEC', or
'BQS-APR'.
Returns
-------
float
"""; 19, assignment; 20, binary_operator:(self.anlzd_ret() - threshold) / stdev; 21, identifier:stdev; 22, call; 23, parenthesized_expression; 24, identifier:stdev; 25, attribute; 26, argument_list; 27, binary_operator:self.anlzd_ret() - threshold; 28, identifier:self; 29, identifier:semi_stdev; 30, keyword_argument; 31, keyword_argument; 32, keyword_argument; 33, call; 34, identifier:threshold; 35, identifier:threshold; 36, identifier:threshold; 37, identifier:ddof; 38, identifier:ddof; 39, identifier:freq; 40, identifier:freq; 41, attribute; 42, argument_list; 43, identifier:self; 44, identifier:anlzd_ret | 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; 20, 23; 20, 24; 22, 25; 22, 26; 23, 27; 25, 28; 25, 29; 26, 30; 26, 31; 26, 32; 27, 33; 27, 34; 30, 35; 30, 36; 31, 37; 31, 38; 32, 39; 32, 40; 33, 41; 33, 42; 41, 43; 41, 44 | def sortino_ratio(self, threshold=0.0, ddof=0, freq=None):
"""Return over a threshold per unit of downside deviation.
A performance appraisal ratio that replaces standard deviation
in the Sharpe ratio with downside deviation.
[Source: CFA Institute]
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
While zero is the default, it is also customary to use
a "minimum acceptable return" (MAR) or a risk-free rate.
Note: this is assumed to be a *periodic*, not necessarily
annualized, return.
ddof : int, default 0
Degrees of freedom, passed to pd.Series.std().
freq : str or None, default None
A frequency string used to create an annualization factor.
If None, `self.freq` will be used. If that is also None,
a frequency will be inferred. If none can be inferred,
an exception is raised.
It may be any frequency string or anchored offset string
recognized by Pandas, such as 'D', '5D', 'Q', 'Q-DEC', or
'BQS-APR'.
Returns
-------
float
"""
stdev = self.semi_stdev(threshold=threshold, ddof=ddof, freq=freq)
return (self.anlzd_ret() - threshold) / stdev |
0, module; 1, function_definition; 2, function_name:sort; 3, parameters; 4, block; 5, identifier:self; 6, identifier:columnId; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, identifier:order; 16, attribute; 17, comment:"""
Sorts the model column
After sorting the data in ascending or descending order, a signal
`layoutChanged` is emitted.
:param: columnId (int)
the index of the column to sort on.
:param: order (Qt::SortOrder, optional)
descending(1) or ascending(0). defaults to Qt.AscendingOrder
"""; 18, call; 19, call; 20, assignment; 21, call; 22, call; 23, call; 24, identifier:Qt; 25, identifier:AscendingOrder; 26, attribute; 27, argument_list; 28, attribute; 29, argument_list; 30, identifier:column; 31, subscript; 32, attribute; 33, argument_list; 34, attribute; 35, argument_list; 36, attribute; 37, argument_list; 38, attribute; 39, identifier:emit; 40, attribute; 41, identifier:emit; 42, attribute; 43, identifier:columnId; 44, attribute; 45, identifier:sort_values; 46, identifier:column; 47, keyword_argument; 48, keyword_argument; 49, attribute; 50, identifier:emit; 51, attribute; 52, identifier:emit; 53, identifier:self; 54, identifier:layoutAboutToBeChanged; 55, identifier:self; 56, identifier:sortingAboutToStart; 57, attribute; 58, identifier:columns; 59, identifier:self; 60, identifier:_dataFrame; 61, identifier:ascending; 62, not_operator; 63, identifier:inplace; 64, True; 65, identifier:self; 66, identifier:layoutChanged; 67, identifier:self; 68, identifier:sortingFinished; 69, identifier:self; 70, identifier:_dataFrame; 71, call; 72, identifier:bool; 73, argument_list; 74, identifier:order | 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; 14, 23; 16, 24; 16, 25; 18, 26; 18, 27; 19, 28; 19, 29; 20, 30; 20, 31; 21, 32; 21, 33; 22, 34; 22, 35; 23, 36; 23, 37; 26, 38; 26, 39; 28, 40; 28, 41; 31, 42; 31, 43; 32, 44; 32, 45; 33, 46; 33, 47; 33, 48; 34, 49; 34, 50; 36, 51; 36, 52; 38, 53; 38, 54; 40, 55; 40, 56; 42, 57; 42, 58; 44, 59; 44, 60; 47, 61; 47, 62; 48, 63; 48, 64; 49, 65; 49, 66; 51, 67; 51, 68; 57, 69; 57, 70; 62, 71; 71, 72; 71, 73; 73, 74 | def sort(self, columnId, order=Qt.AscendingOrder):
"""
Sorts the model column
After sorting the data in ascending or descending order, a signal
`layoutChanged` is emitted.
:param: columnId (int)
the index of the column to sort on.
:param: order (Qt::SortOrder, optional)
descending(1) or ascending(0). defaults to Qt.AscendingOrder
"""
self.layoutAboutToBeChanged.emit()
self.sortingAboutToStart.emit()
column = self._dataFrame.columns[columnId]
self._dataFrame.sort_values(column, ascending=not bool(order), inplace=True)
self.layoutChanged.emit()
self.sortingFinished.emit() |
0, module; 1, function_definition; 2, function_name:run; 3, parameters; 4, block; 5, identifier:self; 6, identifier:clf; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, expression_statement; 11, expression_statement; 12, if_statement; 13, comment:# obtain a 3D array with accuracy numbers; 14, expression_statement; 15, comment:# get result tuple list from the volume; 16, expression_statement; 17, expression_statement; 18, if_statement; 19, return_statement; 20, comment:""" run activity-based voxel selection
Sort the voxels based on the cross-validation accuracy
of their activity vectors within the searchlight
Parameters
----------
clf: classification function
the classifier to be used in cross validation
Returns
-------
result_volume: 3D array of accuracy numbers
contains the voxelwise accuracy numbers obtained via Searchlight
results: list of tuple (voxel_id, accuracy)
the accuracy numbers of all voxels, in accuracy descending order
the length of array equals the number of voxels
"""; 21, assignment; 22, comparison_operator:rank == 0; 23, block; 24, call; 25, call; 26, comparison_operator:rank == 0; 27, block; 28, assignment; 29, assignment; 30, assignment; 31, comparison_operator:rank == 0; 32, block; 33, expression_list; 34, identifier:rank; 35, call; 36, identifier:rank; 37, integer:0; 38, expression_statement; 39, attribute; 40, argument_list; 41, attribute; 42, argument_list; 43, identifier:rank; 44, integer:0; 45, expression_statement; 46, identifier:result_volume; 47, call; 48, identifier:result_list; 49, subscript; 50, identifier:results; 51, list; 52, identifier:rank; 53, integer:0; 54, for_statement; 55, comment:# Sort the voxels; 56, expression_statement; 57, expression_statement; 58, identifier:result_volume; 59, identifier:results; 60, attribute; 61, argument_list; 62, call; 63, attribute; 64, identifier:distribute; 65, list; 66, attribute; 67, attribute; 68, identifier:broadcast; 69, tuple; 70, call; 71, attribute; 72, argument_list; 73, identifier:result_volume; 74, attribute; 75, pattern_list; 76, call; 77, block; 78, call; 79, call; 80, attribute; 81, identifier:Get_rank; 82, attribute; 83, argument_list; 84, identifier:self; 85, identifier:sl; 86, attribute; 87, identifier:self; 88, identifier:mask; 89, identifier:self; 90, identifier:sl; 91, attribute; 92, attribute; 93, identifier:clf; 94, attribute; 95, argument_list; 96, attribute; 97, identifier:run_searchlight; 98, identifier:_sfn; 99, identifier:self; 100, identifier:mask; 101, identifier:idx; 102, identifier:value; 103, identifier:enumerate; 104, argument_list; 105, if_statement; 106, expression_statement; 107, attribute; 108, argument_list; 109, attribute; 110, argument_list; 111, identifier:MPI; 112, identifier:COMM_WORLD; 113, identifier:logger; 114, identifier:info; 115, string; 116, identifier:self; 117, identifier:data; 118, identifier:self; 119, identifier:labels; 120, identifier:self; 121, identifier:num_folds; 122, identifier:logger; 123, identifier:info; 124, string; 125, identifier:self; 126, identifier:sl; 127, identifier:result_list; 128, comparison_operator:value is None; 129, block; 130, call; 131, identifier:results; 132, identifier:sort; 133, keyword_argument; 134, keyword_argument; 135, identifier:logger; 136, identifier:info; 137, string; 138, string_content:running activity-based voxel selection via Searchlight; 139, string_content:data preparation done; 140, identifier:value; 141, None; 142, expression_statement; 143, attribute; 144, argument_list; 145, identifier:key; 146, lambda; 147, identifier:reverse; 148, True; 149, string_content:activity-based voxel selection via Searchlight is done; 150, assignment; 151, identifier:results; 152, identifier:append; 153, tuple; 154, lambda_parameters; 155, subscript; 156, identifier:value; 157, integer:0; 158, identifier:idx; 159, identifier:value; 160, identifier:tup; 161, identifier:tup; 162, integer:1 | 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; 7, 20; 8, 21; 9, 22; 9, 23; 10, 24; 11, 25; 12, 26; 12, 27; 14, 28; 16, 29; 17, 30; 18, 31; 18, 32; 19, 33; 21, 34; 21, 35; 22, 36; 22, 37; 23, 38; 24, 39; 24, 40; 25, 41; 25, 42; 26, 43; 26, 44; 27, 45; 28, 46; 28, 47; 29, 48; 29, 49; 30, 50; 30, 51; 31, 52; 31, 53; 32, 54; 32, 55; 32, 56; 32, 57; 33, 58; 33, 59; 35, 60; 35, 61; 38, 62; 39, 63; 39, 64; 40, 65; 40, 66; 41, 67; 41, 68; 42, 69; 45, 70; 47, 71; 47, 72; 49, 73; 49, 74; 54, 75; 54, 76; 54, 77; 56, 78; 57, 79; 60, 80; 60, 81; 62, 82; 62, 83; 63, 84; 63, 85; 65, 86; 66, 87; 66, 88; 67, 89; 67, 90; 69, 91; 69, 92; 69, 93; 70, 94; 70, 95; 71, 96; 71, 97; 72, 98; 74, 99; 74, 100; 75, 101; 75, 102; 76, 103; 76, 104; 77, 105; 77, 106; 78, 107; 78, 108; 79, 109; 79, 110; 80, 111; 80, 112; 82, 113; 82, 114; 83, 115; 86, 116; 86, 117; 91, 118; 91, 119; 92, 120; 92, 121; 94, 122; 94, 123; 95, 124; 96, 125; 96, 126; 104, 127; 105, 128; 105, 129; 106, 130; 107, 131; 107, 132; 108, 133; 108, 134; 109, 135; 109, 136; 110, 137; 115, 138; 124, 139; 128, 140; 128, 141; 129, 142; 130, 143; 130, 144; 133, 145; 133, 146; 134, 147; 134, 148; 137, 149; 142, 150; 143, 151; 143, 152; 144, 153; 146, 154; 146, 155; 150, 156; 150, 157; 153, 158; 153, 159; 154, 160; 155, 161; 155, 162 | def run(self, clf):
""" run activity-based voxel selection
Sort the voxels based on the cross-validation accuracy
of their activity vectors within the searchlight
Parameters
----------
clf: classification function
the classifier to be used in cross validation
Returns
-------
result_volume: 3D array of accuracy numbers
contains the voxelwise accuracy numbers obtained via Searchlight
results: list of tuple (voxel_id, accuracy)
the accuracy numbers of all voxels, in accuracy descending order
the length of array equals the number of voxels
"""
rank = MPI.COMM_WORLD.Get_rank()
if rank == 0:
logger.info(
'running activity-based voxel selection via Searchlight'
)
self.sl.distribute([self.data], self.mask)
self.sl.broadcast((self.labels, self.num_folds, clf))
if rank == 0:
logger.info(
'data preparation done'
)
# obtain a 3D array with accuracy numbers
result_volume = self.sl.run_searchlight(_sfn)
# get result tuple list from the volume
result_list = result_volume[self.mask]
results = []
if rank == 0:
for idx, value in enumerate(result_list):
if value is None:
value = 0
results.append((idx, value))
# Sort the voxels
results.sort(key=lambda tup: tup[1], reverse=True)
logger.info(
'activity-based voxel selection via Searchlight is done'
)
return result_volume, results |
0, module; 1, function_definition; 2, function_name:run; 3, parameters; 4, block; 5, identifier:self; 6, identifier:clf; 7, expression_statement; 8, expression_statement; 9, if_statement; 10, return_statement; 11, comment:"""Run correlation-based voxel selection in master-worker model.
Sort the voxels based on the cross-validation accuracy
of their correlation vectors
Parameters
----------
clf: classification function
the classifier to be used in cross validation
Returns
-------
results: list of tuple (voxel_id, accuracy)
the accuracy numbers of all voxels, in accuracy descending order
the length of array equals the number of voxels
"""; 12, assignment; 13, comparison_operator:rank == self.master_rank; 14, block; 15, else_clause; 16, identifier:results; 17, identifier:rank; 18, call; 19, identifier:rank; 20, attribute; 21, expression_statement; 22, comment:# Sort the voxels; 23, expression_statement; 24, block; 25, attribute; 26, argument_list; 27, identifier:self; 28, identifier:master_rank; 29, assignment; 30, call; 31, expression_statement; 32, expression_statement; 33, attribute; 34, identifier:Get_rank; 35, identifier:results; 36, call; 37, attribute; 38, argument_list; 39, call; 40, assignment; 41, identifier:MPI; 42, identifier:COMM_WORLD; 43, attribute; 44, argument_list; 45, identifier:results; 46, identifier:sort; 47, keyword_argument; 48, keyword_argument; 49, attribute; 50, argument_list; 51, identifier:results; 52, list; 53, identifier:self; 54, identifier:_master; 55, identifier:key; 56, lambda; 57, identifier:reverse; 58, True; 59, identifier:self; 60, identifier:_worker; 61, identifier:clf; 62, lambda_parameters; 63, subscript; 64, identifier:tup; 65, identifier:tup; 66, 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; 9, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 13, 19; 13, 20; 14, 21; 14, 22; 14, 23; 15, 24; 18, 25; 18, 26; 20, 27; 20, 28; 21, 29; 23, 30; 24, 31; 24, 32; 25, 33; 25, 34; 29, 35; 29, 36; 30, 37; 30, 38; 31, 39; 32, 40; 33, 41; 33, 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; 47, 55; 47, 56; 48, 57; 48, 58; 49, 59; 49, 60; 50, 61; 56, 62; 56, 63; 62, 64; 63, 65; 63, 66 | def run(self, clf):
"""Run correlation-based voxel selection in master-worker model.
Sort the voxels based on the cross-validation accuracy
of their correlation vectors
Parameters
----------
clf: classification function
the classifier to be used in cross validation
Returns
-------
results: list of tuple (voxel_id, accuracy)
the accuracy numbers of all voxels, in accuracy descending order
the length of array equals the number of voxels
"""
rank = MPI.COMM_WORLD.Get_rank()
if rank == self.master_rank:
results = self._master()
# Sort the voxels
results.sort(key=lambda tup: tup[1], reverse=True)
else:
self._worker(clf)
results = []
return results |
0, module; 1, function_definition; 2, function_name:sort; 3, parameters; 4, block; 5, identifier:self; 6, identifier:column_or_label; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, if_statement; 12, assert_statement; 13, if_statement; 14, return_statement; 15, identifier:descending; 16, False; 17, identifier:distinct; 18, False; 19, comment:"""Return a Table of rows sorted according to the values in a column.
Args:
``column_or_label``: the column whose values are used for sorting.
``descending``: if True, sorting will be in descending, rather than
ascending order.
``distinct``: if True, repeated values in ``column_or_label`` will
be omitted.
Returns:
An instance of ``Table`` containing rows sorted based on the values
in ``column_or_label``.
>>> marbles = Table().with_columns(
... "Color", make_array("Red", "Green", "Blue", "Red", "Green", "Green"),
... "Shape", make_array("Round", "Rectangular", "Rectangular", "Round", "Rectangular", "Round"),
... "Amount", make_array(4, 6, 12, 7, 9, 2),
... "Price", make_array(1.30, 1.30, 2.00, 1.75, 1.40, 1.00))
>>> marbles
Color | Shape | Amount | Price
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Blue | Rectangular | 12 | 2
Red | Round | 7 | 1.75
Green | Rectangular | 9 | 1.4
Green | Round | 2 | 1
>>> marbles.sort("Amount")
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Red | Round | 7 | 1.75
Green | Rectangular | 9 | 1.4
Blue | Rectangular | 12 | 2
>>> marbles.sort("Amount", descending = True)
Color | Shape | Amount | Price
Blue | Rectangular | 12 | 2
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Green | Rectangular | 6 | 1.3
Red | Round | 4 | 1.3
Green | Round | 2 | 1
>>> marbles.sort(3) # the Price column
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Blue | Rectangular | 12 | 2
>>> marbles.sort(3, distinct = True)
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Blue | Rectangular | 12 | 2
"""; 20, assignment; 21, identifier:distinct; 22, block; 23, else_clause; 24, call; 25, identifier:row_numbers; 26, identifier:descending; 27, block; 28, call; 29, identifier:column; 30, call; 31, expression_statement; 32, block; 33, attribute; 34, argument_list; 35, expression_statement; 36, attribute; 37, argument_list; 38, attribute; 39, argument_list; 40, assignment; 41, expression_statement; 42, parenthesized_expression; 43, identifier:all; 44, assignment; 45, identifier:self; 46, identifier:take; 47, identifier:row_numbers; 48, identifier:self; 49, identifier:_get_column; 50, identifier:column_or_label; 51, pattern_list; 52, call; 53, assignment; 54, comparison_operator:row_numbers < self.num_rows; 55, identifier:row_numbers; 56, call; 57, identifier:_; 58, identifier:row_numbers; 59, attribute; 60, argument_list; 61, identifier:row_numbers; 62, call; 63, identifier:row_numbers; 64, attribute; 65, attribute; 66, argument_list; 67, identifier:np; 68, identifier:unique; 69, identifier:column; 70, keyword_argument; 71, attribute; 72, argument_list; 73, identifier:self; 74, identifier:num_rows; 75, identifier:np; 76, identifier:array; 77, subscript; 78, identifier:return_index; 79, True; 80, identifier:np; 81, identifier:argsort; 82, identifier:column; 83, keyword_argument; 84, keyword_argument; 85, identifier:row_numbers; 86, slice; 87, identifier:axis; 88, integer:0; 89, identifier:kind; 90, string; 91, unary_operator; 92, string_content:mergesort; 93, 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; 7, 15; 7, 16; 8, 17; 8, 18; 9, 19; 10, 20; 11, 21; 11, 22; 11, 23; 12, 24; 12, 25; 13, 26; 13, 27; 14, 28; 20, 29; 20, 30; 22, 31; 23, 32; 24, 33; 24, 34; 27, 35; 28, 36; 28, 37; 30, 38; 30, 39; 31, 40; 32, 41; 33, 42; 33, 43; 35, 44; 36, 45; 36, 46; 37, 47; 38, 48; 38, 49; 39, 50; 40, 51; 40, 52; 41, 53; 42, 54; 44, 55; 44, 56; 51, 57; 51, 58; 52, 59; 52, 60; 53, 61; 53, 62; 54, 63; 54, 64; 56, 65; 56, 66; 59, 67; 59, 68; 60, 69; 60, 70; 62, 71; 62, 72; 64, 73; 64, 74; 65, 75; 65, 76; 66, 77; 70, 78; 70, 79; 71, 80; 71, 81; 72, 82; 72, 83; 72, 84; 77, 85; 77, 86; 83, 87; 83, 88; 84, 89; 84, 90; 86, 91; 90, 92; 91, 93 | def sort(self, column_or_label, descending=False, distinct=False):
"""Return a Table of rows sorted according to the values in a column.
Args:
``column_or_label``: the column whose values are used for sorting.
``descending``: if True, sorting will be in descending, rather than
ascending order.
``distinct``: if True, repeated values in ``column_or_label`` will
be omitted.
Returns:
An instance of ``Table`` containing rows sorted based on the values
in ``column_or_label``.
>>> marbles = Table().with_columns(
... "Color", make_array("Red", "Green", "Blue", "Red", "Green", "Green"),
... "Shape", make_array("Round", "Rectangular", "Rectangular", "Round", "Rectangular", "Round"),
... "Amount", make_array(4, 6, 12, 7, 9, 2),
... "Price", make_array(1.30, 1.30, 2.00, 1.75, 1.40, 1.00))
>>> marbles
Color | Shape | Amount | Price
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Blue | Rectangular | 12 | 2
Red | Round | 7 | 1.75
Green | Rectangular | 9 | 1.4
Green | Round | 2 | 1
>>> marbles.sort("Amount")
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Red | Round | 7 | 1.75
Green | Rectangular | 9 | 1.4
Blue | Rectangular | 12 | 2
>>> marbles.sort("Amount", descending = True)
Color | Shape | Amount | Price
Blue | Rectangular | 12 | 2
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Green | Rectangular | 6 | 1.3
Red | Round | 4 | 1.3
Green | Round | 2 | 1
>>> marbles.sort(3) # the Price column
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Blue | Rectangular | 12 | 2
>>> marbles.sort(3, distinct = True)
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Blue | Rectangular | 12 | 2
"""
column = self._get_column(column_or_label)
if distinct:
_, row_numbers = np.unique(column, return_index=True)
else:
row_numbers = np.argsort(column, axis=0, kind='mergesort')
assert (row_numbers < self.num_rows).all(), row_numbers
if descending:
row_numbers = np.array(row_numbers[::-1])
return self.take(row_numbers) |
0, module; 1, function_definition; 2, function_name:_sub_expand; 3, parameters; 4, block; 5, identifier:self; 6, identifier:tags; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, comment:# name entities; 11, for_statement; 12, for_statement; 13, comment:"""This called by expand to find cliques
Args:
tags (list): a list of the tags used to get cliques
Yields:
list : list of sorted tags by start_token this is a clique
"""; 14, assignment; 15, assignment; 16, identifier:tag; 17, identifier:tags; 18, block; 19, identifier:clique; 20, call; 21, block; 22, identifier:entities; 23, dictionary; 24, identifier:graph; 25, call; 26, for_statement; 27, identifier:get_cliques; 28, argument_list; 29, expression_statement; 30, for_statement; 31, expression_statement; 32, expression_statement; 33, attribute; 34, argument_list; 35, identifier:entity_index; 36, call; 37, block; 38, call; 39, identifier:graph; 40, assignment; 41, identifier:entity_name; 42, identifier:clique; 43, block; 44, assignment; 45, yield; 46, identifier:self; 47, identifier:_build_graph; 48, identifier:tags; 49, identifier:xrange; 50, argument_list; 51, expression_statement; 52, if_statement; 53, expression_statement; 54, identifier:list; 55, argument_list; 56, identifier:result; 57, list; 58, expression_statement; 59, expression_statement; 60, expression_statement; 61, expression_statement; 62, identifier:result; 63, call; 64, identifier:result; 65, call; 66, assignment; 67, not_operator; 68, block; 69, augmented_assignment; 70, identifier:entities; 71, assignment; 72, assignment; 73, assignment; 74, call; 75, identifier:sorted; 76, argument_list; 77, identifier:len; 78, argument_list; 79, identifier:node_name; 80, call; 81, comparison_operator:node_name in entities; 82, expression_statement; 83, subscript; 84, list; 85, identifier:start_token; 86, call; 87, identifier:old_tag; 88, subscript; 89, identifier:tag; 90, dictionary; 91, attribute; 92, argument_list; 93, identifier:result; 94, keyword_argument; 95, call; 96, identifier:graph_key_from_tag; 97, argument_list; 98, identifier:node_name; 99, identifier:entities; 100, assignment; 101, identifier:entities; 102, identifier:node_name; 103, subscript; 104, call; 105, identifier:tag; 106, identifier:int; 107, argument_list; 108, subscript; 109, integer:2; 110, pair; 111, pair; 112, pair; 113, pair; 114, pair; 115, pair; 116, pair; 117, identifier:result; 118, identifier:append; 119, identifier:tag; 120, identifier:key; 121, lambda; 122, attribute; 123, argument_list; 124, identifier:tag; 125, identifier:entity_index; 126, subscript; 127, list; 128, call; 129, identifier:entity_index; 130, attribute; 131, argument_list; 132, subscript; 133, identifier:entities; 134, identifier:entity_name; 135, string; 136, identifier:start_token; 137, string; 138, list; 139, string; 140, binary_operator:entities.get(entity_name)[1] * old_tag.get('confidence', 1.0); 141, string; 142, call; 143, string; 144, call; 145, string; 146, call; 147, string; 148, call; 149, lambda_parameters; 150, call; 151, identifier:tag; 152, identifier:get; 153, string; 154, identifier:entities; 155, identifier:node_name; 156, attribute; 157, argument_list; 158, subscript; 159, identifier:get; 160, string; 161, call; 162, integer:0; 163, string_content:start_token; 164, string_content:entities; 165, subscript; 166, string_content:confidence; 167, subscript; 168, call; 169, string_content:end_token; 170, attribute; 171, argument_list; 172, string_content:match; 173, attribute; 174, argument_list; 175, string_content:key; 176, attribute; 177, argument_list; 178, string_content:from_context; 179, attribute; 180, argument_list; 181, identifier:e; 182, attribute; 183, argument_list; 184, string_content:entities; 185, identifier:tag; 186, identifier:get; 187, string; 188, list; 189, call; 190, identifier:entity_index; 191, string_content:confidence; 192, attribute; 193, argument_list; 194, call; 195, integer:0; 196, call; 197, integer:1; 198, attribute; 199, argument_list; 200, identifier:old_tag; 201, identifier:get; 202, string; 203, subscript; 204, identifier:get; 205, string; 206, subscript; 207, identifier:get; 208, string; 209, identifier:old_tag; 210, identifier:get; 211, string; 212, False; 213, identifier:e; 214, identifier:get; 215, string; 216, string_content:entities; 217, attribute; 218, argument_list; 219, identifier:entity_name; 220, identifier:split; 221, string:"-"; 222, attribute; 223, argument_list; 224, attribute; 225, argument_list; 226, identifier:old_tag; 227, identifier:get; 228, string; 229, float:1.0; 230, string_content:end_token; 231, call; 232, integer:0; 233, string_content:match; 234, call; 235, integer:0; 236, string_content:key; 237, string_content:from_context; 238, string_content:start_token; 239, identifier:tag; 240, identifier:get; 241, string; 242, list; 243, identifier:entities; 244, identifier:get; 245, identifier:entity_name; 246, identifier:entities; 247, identifier:get; 248, identifier:entity_name; 249, string_content:confidence; 250, attribute; 251, argument_list; 252, attribute; 253, argument_list; 254, string_content:entities; 255, identifier:old_tag; 256, identifier:get; 257, string; 258, identifier:old_tag; 259, identifier:get; 260, string; 261, string_content:entities; 262, string_content:entities | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 7, 13; 8, 14; 9, 15; 11, 16; 11, 17; 11, 18; 12, 19; 12, 20; 12, 21; 14, 22; 14, 23; 15, 24; 15, 25; 18, 26; 20, 27; 20, 28; 21, 29; 21, 30; 21, 31; 21, 32; 25, 33; 25, 34; 26, 35; 26, 36; 26, 37; 28, 38; 28, 39; 29, 40; 30, 41; 30, 42; 30, 43; 31, 44; 32, 45; 33, 46; 33, 47; 34, 48; 36, 49; 36, 50; 37, 51; 37, 52; 37, 53; 38, 54; 38, 55; 40, 56; 40, 57; 43, 58; 43, 59; 43, 60; 43, 61; 44, 62; 44, 63; 45, 64; 50, 65; 51, 66; 52, 67; 52, 68; 53, 69; 55, 70; 58, 71; 59, 72; 60, 73; 61, 74; 63, 75; 63, 76; 65, 77; 65, 78; 66, 79; 66, 80; 67, 81; 68, 82; 69, 83; 69, 84; 71, 85; 71, 86; 72, 87; 72, 88; 73, 89; 73, 90; 74, 91; 74, 92; 76, 93; 76, 94; 78, 95; 80, 96; 80, 97; 81, 98; 81, 99; 82, 100; 83, 101; 83, 102; 84, 103; 84, 104; 84, 105; 86, 106; 86, 107; 88, 108; 88, 109; 90, 110; 90, 111; 90, 112; 90, 113; 90, 114; 90, 115; 90, 116; 91, 117; 91, 118; 92, 119; 94, 120; 94, 121; 95, 122; 95, 123; 97, 124; 97, 125; 100, 126; 100, 127; 103, 128; 103, 129; 104, 130; 104, 131; 107, 132; 108, 133; 108, 134; 110, 135; 110, 136; 111, 137; 111, 138; 112, 139; 112, 140; 113, 141; 113, 142; 114, 143; 114, 144; 115, 145; 115, 146; 116, 147; 116, 148; 121, 149; 121, 150; 122, 151; 122, 152; 123, 153; 126, 154; 126, 155; 128, 156; 128, 157; 130, 158; 130, 159; 131, 160; 132, 161; 132, 162; 135, 163; 137, 164; 138, 165; 139, 166; 140, 167; 140, 168; 141, 169; 142, 170; 142, 171; 143, 172; 144, 173; 144, 174; 145, 175; 146, 176; 146, 177; 147, 178; 148, 179; 148, 180; 149, 181; 150, 182; 150, 183; 153, 184; 156, 185; 156, 186; 157, 187; 157, 188; 158, 189; 158, 190; 160, 191; 161, 192; 161, 193; 165, 194; 165, 195; 167, 196; 167, 197; 168, 198; 168, 199; 170, 200; 170, 201; 171, 202; 173, 203; 173, 204; 174, 205; 176, 206; 176, 207; 177, 208; 179, 209; 179, 210; 180, 211; 180, 212; 182, 213; 182, 214; 183, 215; 187, 216; 189, 217; 189, 218; 192, 219; 192, 220; 193, 221; 194, 222; 194, 223; 196, 224; 196, 225; 198, 226; 198, 227; 199, 228; 199, 229; 202, 230; 203, 231; 203, 232; 205, 233; 206, 234; 206, 235; 208, 236; 211, 237; 215, 238; 217, 239; 217, 240; 218, 241; 218, 242; 222, 243; 222, 244; 223, 245; 224, 246; 224, 247; 225, 248; 228, 249; 231, 250; 231, 251; 234, 252; 234, 253; 241, 254; 250, 255; 250, 256; 251, 257; 252, 258; 252, 259; 253, 260; 257, 261; 260, 262 | def _sub_expand(self, tags):
"""This called by expand to find cliques
Args:
tags (list): a list of the tags used to get cliques
Yields:
list : list of sorted tags by start_token this is a clique
"""
entities = {}
graph = self._build_graph(tags)
# name entities
for tag in tags:
for entity_index in xrange(len(tag.get('entities'))):
node_name = graph_key_from_tag(tag, entity_index)
if not node_name in entities:
entities[node_name] = []
entities[node_name] += [
tag.get('entities', [])[entity_index],
tag.get('entities', [])[entity_index].get('confidence'),
tag
]
for clique in get_cliques(list(entities), graph):
result = []
for entity_name in clique:
start_token = int(entity_name.split("-")[0])
old_tag = entities[entity_name][2]
tag = {
'start_token': start_token,
'entities': [entities.get(entity_name)[0]],
'confidence': entities.get(entity_name)[1] * old_tag.get('confidence', 1.0),
'end_token': old_tag.get('end_token'),
'match': old_tag.get('entities')[0].get('match'),
'key': old_tag.get('entities')[0].get('key'),
'from_context': old_tag.get('from_context', False)
}
result.append(tag)
result = sorted(result, key=lambda e: e.get('start_token'))
yield result |
0, module; 1, function_definition; 2, function_name:_rank_results; 3, parameters; 4, type; 5, block; 6, typed_parameter; 7, typed_parameter; 8, generic_type; 9, expression_statement; 10, comment:# https://stackoverflow.com/a/73050; 11, expression_statement; 12, if_statement; 13, return_statement; 14, identifier:results; 15, type; 16, identifier:method; 17, type; 18, identifier:List; 19, type_parameter; 20, comment:"""
Ranks results - for phenodigm results are ranks but ties need to accounted for
for other methods, results need to be reranked
:param results: Results from search_by_attribute_set()['results'] or
compare_attribute_sets()['results']
:param method: sim method used to rank results
:return: Sorted results list
"""; 21, assignment; 22, comparison_operator:len(sorted_results) > 0; 23, block; 24, identifier:sorted_results; 25, generic_type; 26, identifier:SimAlgorithm; 27, type; 28, identifier:sorted_results; 29, call; 30, call; 31, integer:0; 32, expression_statement; 33, expression_statement; 34, for_statement; 35, identifier:List; 36, type_parameter; 37, identifier:Dict; 38, identifier:sorted; 39, argument_list; 40, identifier:len; 41, argument_list; 42, assignment; 43, assignment; 44, identifier:result; 45, identifier:sorted_results; 46, block; 47, type; 48, identifier:results; 49, keyword_argument; 50, keyword_argument; 51, identifier:sorted_results; 52, identifier:rank; 53, integer:1; 54, identifier:previous_score; 55, subscript; 56, if_statement; 57, expression_statement; 58, expression_statement; 59, identifier:Dict; 60, identifier:reverse; 61, True; 62, identifier:key; 63, lambda; 64, subscript; 65, subscript; 66, comparison_operator:previous_score > result[OwlSim2Api.method2key[method]]; 67, block; 68, assignment; 69, assignment; 70, lambda_parameters; 71, subscript; 72, identifier:sorted_results; 73, integer:0; 74, attribute; 75, identifier:method; 76, identifier:previous_score; 77, subscript; 78, expression_statement; 79, subscript; 80, identifier:rank; 81, identifier:previous_score; 82, subscript; 83, identifier:k; 84, identifier:k; 85, subscript; 86, identifier:OwlSim2Api; 87, identifier:method2key; 88, identifier:result; 89, subscript; 90, augmented_assignment; 91, identifier:result; 92, string; 93, identifier:result; 94, subscript; 95, attribute; 96, identifier:method; 97, attribute; 98, identifier:method; 99, identifier:rank; 100, integer:1; 101, string_content:rank; 102, attribute; 103, identifier:method; 104, identifier:OwlSim2Api; 105, identifier:method2key; 106, identifier:OwlSim2Api; 107, identifier:method2key; 108, identifier:OwlSim2Api; 109, identifier:method2key | 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; 6, 14; 6, 15; 7, 16; 7, 17; 8, 18; 8, 19; 9, 20; 11, 21; 12, 22; 12, 23; 13, 24; 15, 25; 17, 26; 19, 27; 21, 28; 21, 29; 22, 30; 22, 31; 23, 32; 23, 33; 23, 34; 25, 35; 25, 36; 27, 37; 29, 38; 29, 39; 30, 40; 30, 41; 32, 42; 33, 43; 34, 44; 34, 45; 34, 46; 36, 47; 39, 48; 39, 49; 39, 50; 41, 51; 42, 52; 42, 53; 43, 54; 43, 55; 46, 56; 46, 57; 46, 58; 47, 59; 49, 60; 49, 61; 50, 62; 50, 63; 55, 64; 55, 65; 56, 66; 56, 67; 57, 68; 58, 69; 63, 70; 63, 71; 64, 72; 64, 73; 65, 74; 65, 75; 66, 76; 66, 77; 67, 78; 68, 79; 68, 80; 69, 81; 69, 82; 70, 83; 71, 84; 71, 85; 74, 86; 74, 87; 77, 88; 77, 89; 78, 90; 79, 91; 79, 92; 82, 93; 82, 94; 85, 95; 85, 96; 89, 97; 89, 98; 90, 99; 90, 100; 92, 101; 94, 102; 94, 103; 95, 104; 95, 105; 97, 106; 97, 107; 102, 108; 102, 109 | def _rank_results(results: List[Dict], method: SimAlgorithm) -> List[Dict]:
"""
Ranks results - for phenodigm results are ranks but ties need to accounted for
for other methods, results need to be reranked
:param results: Results from search_by_attribute_set()['results'] or
compare_attribute_sets()['results']
:param method: sim method used to rank results
:return: Sorted results list
"""
# https://stackoverflow.com/a/73050
sorted_results = sorted(
results, reverse=True, key=lambda k: k[OwlSim2Api.method2key[method]]
)
if len(sorted_results) > 0:
rank = 1
previous_score = sorted_results[0][OwlSim2Api.method2key[method]]
for result in sorted_results:
if previous_score > result[OwlSim2Api.method2key[method]]:
rank += 1
result['rank'] = rank
previous_score = result[OwlSim2Api.method2key[method]]
return sorted_results |
0, module; 1, function_definition; 2, function_name:sorted_source_files; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, assert_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""Returns a list of targets in topologically sorted order."""; 12, attribute; 13, string; 14, assignment; 15, identifier:node; 16, call; 17, block; 18, call; 19, identifier:self; 20, identifier:final; 21, string_content:Call build() before using the graph.; 22, identifier:out; 23, list; 24, attribute; 25, argument_list; 26, if_statement; 27, identifier:list; 28, argument_list; 29, identifier:nx; 30, identifier:topological_sort; 31, attribute; 32, call; 33, block; 34, else_clause; 35, call; 36, identifier:self; 37, identifier:graph; 38, identifier:isinstance; 39, argument_list; 40, expression_statement; 41, comment:# add a one-element list for uniformity; 42, block; 43, identifier:reversed; 44, argument_list; 45, identifier:node; 46, identifier:NodeSet; 47, call; 48, expression_statement; 49, identifier:out; 50, attribute; 51, argument_list; 52, call; 53, identifier:out; 54, identifier:append; 55, attribute; 56, attribute; 57, argument_list; 58, identifier:node; 59, identifier:nodes; 60, identifier:out; 61, identifier:append; 62, list; 63, identifier:node | 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; 9, 15; 9, 16; 9, 17; 10, 18; 12, 19; 12, 20; 13, 21; 14, 22; 14, 23; 16, 24; 16, 25; 17, 26; 18, 27; 18, 28; 24, 29; 24, 30; 25, 31; 26, 32; 26, 33; 26, 34; 28, 35; 31, 36; 31, 37; 32, 38; 32, 39; 33, 40; 34, 41; 34, 42; 35, 43; 35, 44; 39, 45; 39, 46; 40, 47; 42, 48; 44, 49; 47, 50; 47, 51; 48, 52; 50, 53; 50, 54; 51, 55; 52, 56; 52, 57; 55, 58; 55, 59; 56, 60; 56, 61; 57, 62; 62, 63 | def sorted_source_files(self):
"""Returns a list of targets in topologically sorted order."""
assert self.final, 'Call build() before using the graph.'
out = []
for node in nx.topological_sort(self.graph):
if isinstance(node, NodeSet):
out.append(node.nodes)
else:
# add a one-element list for uniformity
out.append([node])
return list(reversed(out)) |
0, module; 1, function_definition; 2, function_name:expand_source_files; 3, parameters; 4, block; 5, identifier:filenames; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, identifier:cwd; 12, None; 13, comment:"""Expand a list of filenames passed in as sources.
This is a helper function for handling command line arguments that specify a
list of source files and directories.
Any directories in filenames will be scanned recursively for .py files.
Any files that do not end with ".py" will be dropped.
Args:
filenames: A list of filenames to process.
cwd: An optional working directory to expand relative paths
Returns:
A list of sorted full paths to .py files
"""; 14, assignment; 15, identifier:f; 16, call; 17, block; 18, call; 19, identifier:out; 20, list; 21, identifier:expand_paths; 22, argument_list; 23, if_statement; 24, identifier:sorted; 25, argument_list; 26, identifier:filenames; 27, identifier:cwd; 28, call; 29, comment:# If we have a directory, collect all the .py files within it.; 30, block; 31, else_clause; 32, call; 33, attribute; 34, argument_list; 35, expression_statement; 36, block; 37, identifier:set; 38, argument_list; 39, attribute; 40, identifier:isdir; 41, identifier:f; 42, augmented_assignment; 43, if_statement; 44, identifier:out; 45, identifier:os; 46, identifier:path; 47, identifier:out; 48, call; 49, call; 50, block; 51, identifier:collect_files; 52, argument_list; 53, attribute; 54, argument_list; 55, expression_statement; 56, identifier:f; 57, string:".py"; 58, identifier:f; 59, identifier:endswith; 60, string:".py"; 61, call; 62, attribute; 63, argument_list; 64, identifier:out; 65, identifier:append; 66, identifier:f | 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; 9, 17; 10, 18; 14, 19; 14, 20; 16, 21; 16, 22; 17, 23; 18, 24; 18, 25; 22, 26; 22, 27; 23, 28; 23, 29; 23, 30; 23, 31; 25, 32; 28, 33; 28, 34; 30, 35; 31, 36; 32, 37; 32, 38; 33, 39; 33, 40; 34, 41; 35, 42; 36, 43; 38, 44; 39, 45; 39, 46; 42, 47; 42, 48; 43, 49; 43, 50; 48, 51; 48, 52; 49, 53; 49, 54; 50, 55; 52, 56; 52, 57; 53, 58; 53, 59; 54, 60; 55, 61; 61, 62; 61, 63; 62, 64; 62, 65; 63, 66 | def expand_source_files(filenames, cwd=None):
"""Expand a list of filenames passed in as sources.
This is a helper function for handling command line arguments that specify a
list of source files and directories.
Any directories in filenames will be scanned recursively for .py files.
Any files that do not end with ".py" will be dropped.
Args:
filenames: A list of filenames to process.
cwd: An optional working directory to expand relative paths
Returns:
A list of sorted full paths to .py files
"""
out = []
for f in expand_paths(filenames, cwd):
if os.path.isdir(f):
# If we have a directory, collect all the .py files within it.
out += collect_files(f, ".py")
else:
if f.endswith(".py"):
out.append(f)
return sorted(set(out)) |
0, module; 1, function_definition; 2, function_name:run; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, comment:# count before filtering; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, comment:# apply filters; 15, expression_statement; 16, expression_statement; 17, comment:# apply sorts; 18, expression_statement; 19, comment:# add paging options; 20, expression_statement; 21, if_statement; 22, expression_statement; 23, comment:# add columns to query; 24, expression_statement; 25, comment:# fetch the result of the queries; 26, expression_statement; 27, expression_statement; 28, comment:"""Launch filtering, sorting and paging to output results."""; 29, assignment; 30, assignment; 31, call; 32, call; 33, call; 34, call; 35, assignment; 36, assignment; 37, assignment; 38, assignment; 39, comparison_operator:length >= 0; 40, block; 41, elif_clause; 42, else_clause; 43, assignment; 44, assignment; 45, assignment; 46, assignment; 47, identifier:query; 48, attribute; 49, attribute; 50, call; 51, attribute; 52, argument_list; 53, attribute; 54, argument_list; 55, attribute; 56, argument_list; 57, attribute; 58, argument_list; 59, identifier:query; 60, call; 61, attribute; 62, call; 63, identifier:query; 64, call; 65, identifier:length; 66, call; 67, identifier:length; 68, integer:0; 69, expression_statement; 70, comparison_operator:length == -1; 71, block; 72, block; 73, identifier:query; 74, call; 75, identifier:query; 76, call; 77, identifier:column_names; 78, list_comprehension; 79, attribute; 80, list_comprehension; 81, identifier:self; 82, identifier:query; 83, identifier:self; 84, identifier:cardinality; 85, attribute; 86, argument_list; 87, identifier:self; 88, identifier:_set_column_filter_expressions; 89, identifier:self; 90, identifier:_set_global_filter_expression; 91, identifier:self; 92, identifier:_set_sort_expressions; 93, identifier:self; 94, identifier:_set_yadcf_data; 95, identifier:query; 96, attribute; 97, argument_list; 98, identifier:self; 99, identifier:cardinality_filtered; 100, attribute; 101, argument_list; 102, attribute; 103, argument_list; 104, identifier:int; 105, argument_list; 106, assignment; 107, identifier:length; 108, unary_operator; 109, pass_statement; 110, raise_statement; 111, attribute; 112, argument_list; 113, attribute; 114, argument_list; 115, conditional_expression:col.mData if col.mData else str(i); 116, for_in_clause; 117, identifier:self; 118, identifier:results; 119, dictionary_comprehension; 120, for_in_clause; 121, call; 122, identifier:count; 123, identifier:query; 124, identifier:filter; 125, list_splat; 126, call; 127, identifier:count; 128, identifier:query; 129, identifier:order_by; 130, list_splat; 131, call; 132, identifier:query; 133, call; 134, integer:1; 135, parenthesized_expression; 136, identifier:query; 137, identifier:offset; 138, call; 139, identifier:query; 140, identifier:add_columns; 141, list_splat; 142, attribute; 143, attribute; 144, call; 145, pattern_list; 146, call; 147, pair; 148, for_in_clause; 149, identifier:row; 150, call; 151, attribute; 152, argument_list; 153, list_comprehension; 154, attribute; 155, argument_list; 156, list_comprehension; 157, attribute; 158, argument_list; 159, attribute; 160, argument_list; 161, call; 162, identifier:int; 163, argument_list; 164, list_comprehension; 165, identifier:col; 166, identifier:mData; 167, identifier:col; 168, identifier:mData; 169, identifier:str; 170, argument_list; 171, identifier:i; 172, identifier:col; 173, identifier:enumerate; 174, argument_list; 175, identifier:k; 176, identifier:v; 177, pattern_list; 178, call; 179, attribute; 180, argument_list; 181, identifier:query; 182, identifier:add_columns; 183, attribute; 184, identifier:e; 185, for_in_clause; 186, if_clause; 187, identifier:query; 188, identifier:add_columns; 189, attribute; 190, identifier:e; 191, for_in_clause; 192, if_clause; 193, attribute; 194, identifier:get; 195, string; 196, identifier:query; 197, identifier:limit; 198, identifier:length; 199, identifier:ValueError; 200, argument_list; 201, call; 202, attribute; 203, for_in_clause; 204, identifier:i; 205, attribute; 206, identifier:k; 207, identifier:v; 208, identifier:zip; 209, argument_list; 210, identifier:query; 211, identifier:all; 212, subscript; 213, identifier:sqla_expr; 214, identifier:e; 215, attribute; 216, comparison_operator:e is not None; 217, subscript; 218, identifier:sqla_expr; 219, identifier:e; 220, attribute; 221, comparison_operator:e is not None; 222, identifier:self; 223, identifier:params; 224, string_content:length; 225, string; 226, attribute; 227, argument_list; 228, identifier:c; 229, identifier:sqla_expr; 230, identifier:c; 231, attribute; 232, identifier:self; 233, identifier:columns; 234, identifier:column_names; 235, identifier:row; 236, attribute; 237, integer:0; 238, identifier:self; 239, identifier:filter_expressions; 240, identifier:e; 241, None; 242, attribute; 243, integer:0; 244, identifier:self; 245, identifier:sort_expressions; 246, identifier:e; 247, None; 248, string_content:Length should be a positive integer or -1 to disable; 249, attribute; 250, identifier:get; 251, string; 252, identifier:self; 253, identifier:columns; 254, identifier:self; 255, identifier:columns; 256, identifier:self; 257, identifier:columns; 258, identifier:self; 259, identifier:params; 260, string_content:start | 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; 6, 28; 7, 29; 9, 30; 10, 31; 11, 32; 12, 33; 13, 34; 15, 35; 16, 36; 18, 37; 20, 38; 21, 39; 21, 40; 21, 41; 21, 42; 22, 43; 24, 44; 26, 45; 27, 46; 29, 47; 29, 48; 30, 49; 30, 50; 31, 51; 31, 52; 32, 53; 32, 54; 33, 55; 33, 56; 34, 57; 34, 58; 35, 59; 35, 60; 36, 61; 36, 62; 37, 63; 37, 64; 38, 65; 38, 66; 39, 67; 39, 68; 40, 69; 41, 70; 41, 71; 42, 72; 43, 73; 43, 74; 44, 75; 44, 76; 45, 77; 45, 78; 46, 79; 46, 80; 48, 81; 48, 82; 49, 83; 49, 84; 50, 85; 50, 86; 51, 87; 51, 88; 53, 89; 53, 90; 55, 91; 55, 92; 57, 93; 57, 94; 58, 95; 60, 96; 60, 97; 61, 98; 61, 99; 62, 100; 62, 101; 64, 102; 64, 103; 66, 104; 66, 105; 69, 106; 70, 107; 70, 108; 71, 109; 72, 110; 74, 111; 74, 112; 76, 113; 76, 114; 78, 115; 78, 116; 79, 117; 79, 118; 80, 119; 80, 120; 85, 121; 85, 122; 96, 123; 96, 124; 97, 125; 100, 126; 100, 127; 102, 128; 102, 129; 103, 130; 105, 131; 106, 132; 106, 133; 108, 134; 110, 135; 111, 136; 111, 137; 112, 138; 113, 139; 113, 140; 114, 141; 115, 142; 115, 143; 115, 144; 116, 145; 116, 146; 119, 147; 119, 148; 120, 149; 120, 150; 121, 151; 121, 152; 125, 153; 126, 154; 126, 155; 130, 156; 131, 157; 131, 158; 133, 159; 133, 160; 135, 161; 138, 162; 138, 163; 141, 164; 142, 165; 142, 166; 143, 167; 143, 168; 144, 169; 144, 170; 145, 171; 145, 172; 146, 173; 146, 174; 147, 175; 147, 176; 148, 177; 148, 178; 150, 179; 150, 180; 151, 181; 151, 182; 152, 183; 153, 184; 153, 185; 153, 186; 154, 187; 154, 188; 155, 189; 156, 190; 156, 191; 156, 192; 157, 193; 157, 194; 158, 195; 159, 196; 159, 197; 160, 198; 161, 199; 161, 200; 163, 201; 164, 202; 164, 203; 170, 204; 174, 205; 177, 206; 177, 207; 178, 208; 178, 209; 179, 210; 179, 211; 183, 212; 183, 213; 185, 214; 185, 215; 186, 216; 189, 217; 189, 218; 191, 219; 191, 220; 192, 221; 193, 222; 193, 223; 195, 224; 200, 225; 201, 226; 201, 227; 202, 228; 202, 229; 203, 230; 203, 231; 205, 232; 205, 233; 209, 234; 209, 235; 212, 236; 212, 237; 215, 238; 215, 239; 216, 240; 216, 241; 217, 242; 217, 243; 220, 244; 220, 245; 221, 246; 221, 247; 225, 248; 226, 249; 226, 250; 227, 251; 231, 252; 231, 253; 236, 254; 236, 255; 242, 256; 242, 257; 249, 258; 249, 259; 251, 260 | def run(self):
"""Launch filtering, sorting and paging to output results."""
query = self.query
# count before filtering
self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()
self._set_column_filter_expressions()
self._set_global_filter_expression()
self._set_sort_expressions()
self._set_yadcf_data(query)
# apply filters
query = query.filter(
*[e for e in self.filter_expressions if e is not None])
self.cardinality_filtered = query.add_columns(
self.columns[0].sqla_expr).count()
# apply sorts
query = query.order_by(
*[e for e in self.sort_expressions if e is not None])
# add paging options
length = int(self.params.get('length'))
if length >= 0:
query = query.limit(length)
elif length == -1:
pass
else:
raise (ValueError(
'Length should be a positive integer or -1 to disable'))
query = query.offset(int(self.params.get('start')))
# add columns to query
query = query.add_columns(*[c.sqla_expr for c in self.columns])
# fetch the result of the queries
column_names = [
col.mData if col.mData else str(i)
for i, col in enumerate(self.columns)
]
self.results = [{k: v
for k, v in zip(column_names, row)}
for row in query.all()] |
0, module; 1, function_definition; 2, function_name:poll_events; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, while_statement; 8, comment:"""Continuously polls all types of events from sl4a.
Events are sorted by name and store in separate queues.
If there are registered handlers, the handlers will be called with
corresponding event immediately upon event discovery, and the event
won't be stored. If exceptions occur, stop the dispatcher and return
"""; 9, attribute; 10, block; 11, identifier:self; 12, identifier:started; 13, expression_statement; 14, expression_statement; 15, try_statement; 16, if_statement; 17, comment:# if handler registered, process event; 18, if_statement; 19, if_statement; 20, assignment; 21, assignment; 22, block; 23, except_clause; 24, not_operator; 25, block; 26, elif_clause; 27, else_clause; 28, comparison_operator:event_name in self.handlers; 29, block; 30, comparison_operator:event_name == "EventDispatcherShutdown"; 31, block; 32, else_clause; 33, identifier:event_obj; 34, None; 35, identifier:event_name; 36, None; 37, expression_statement; 38, block; 39, identifier:event_obj; 40, continue_statement; 41, comparison_operator:'name' not in event_obj; 42, block; 43, block; 44, identifier:event_name; 45, attribute; 46, expression_statement; 47, identifier:event_name; 48, string:"EventDispatcherShutdown"; 49, expression_statement; 50, break_statement; 51, block; 52, assignment; 53, if_statement; 54, string; 55, identifier:event_obj; 56, expression_statement; 57, continue_statement; 58, expression_statement; 59, identifier:self; 60, identifier:handlers; 61, call; 62, call; 63, expression_statement; 64, if_statement; 65, expression_statement; 66, identifier:event_obj; 67, call; 68, attribute; 69, block; 70, string_content:name; 71, call; 72, assignment; 73, attribute; 74, argument_list; 75, attribute; 76, argument_list; 77, call; 78, comparison_operator:event_name in self.event_dict; 79, comment:# otherwise, cache event; 80, block; 81, else_clause; 82, call; 83, attribute; 84, argument_list; 85, identifier:self; 86, identifier:started; 87, expression_statement; 88, expression_statement; 89, raise_statement; 90, identifier:print; 91, argument_list; 92, identifier:event_name; 93, subscript; 94, identifier:self; 95, identifier:handle_subscribed_event; 96, identifier:event_obj; 97, identifier:event_name; 98, attribute; 99, identifier:closeSl4aSession; 100, attribute; 101, argument_list; 102, identifier:event_name; 103, attribute; 104, expression_statement; 105, block; 106, attribute; 107, argument_list; 108, attribute; 109, identifier:eventWait; 110, integer:50000; 111, call; 112, call; 113, call; 114, identifier:event_obj; 115, string; 116, identifier:self; 117, identifier:_sl4a; 118, attribute; 119, identifier:acquire; 120, identifier:self; 121, identifier:event_dict; 122, call; 123, expression_statement; 124, expression_statement; 125, expression_statement; 126, attribute; 127, identifier:release; 128, identifier:self; 129, identifier:_sl4a; 130, identifier:print; 131, argument_list; 132, identifier:print; 133, argument_list; 134, attribute; 135, argument_list; 136, string_content:name; 137, identifier:self; 138, identifier:lock; 139, attribute; 140, argument_list; 141, assignment; 142, call; 143, assignment; 144, identifier:self; 145, identifier:lock; 146, string:"Exception happened during polling."; 147, call; 148, string:"Received Malformed event {}"; 149, identifier:format; 150, identifier:event_obj; 151, subscript; 152, identifier:put; 153, identifier:event_obj; 154, identifier:q; 155, call; 156, attribute; 157, argument_list; 158, subscript; 159, identifier:q; 160, attribute; 161, argument_list; 162, attribute; 163, identifier:event_name; 164, attribute; 165, argument_list; 166, identifier:q; 167, identifier:put; 168, identifier:event_obj; 169, attribute; 170, identifier:event_name; 171, identifier:traceback; 172, identifier:format_exc; 173, identifier:self; 174, identifier:event_dict; 175, identifier:queue; 176, identifier:Queue; 177, identifier:self; 178, identifier:event_dict | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 7, 10; 9, 11; 9, 12; 10, 13; 10, 14; 10, 15; 10, 16; 10, 17; 10, 18; 10, 19; 13, 20; 14, 21; 15, 22; 15, 23; 16, 24; 16, 25; 16, 26; 16, 27; 18, 28; 18, 29; 19, 30; 19, 31; 19, 32; 20, 33; 20, 34; 21, 35; 21, 36; 22, 37; 23, 38; 24, 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; 37, 52; 38, 53; 41, 54; 41, 55; 42, 56; 42, 57; 43, 58; 45, 59; 45, 60; 46, 61; 49, 62; 51, 63; 51, 64; 51, 65; 52, 66; 52, 67; 53, 68; 53, 69; 54, 70; 56, 71; 58, 72; 61, 73; 61, 74; 62, 75; 62, 76; 63, 77; 64, 78; 64, 79; 64, 80; 64, 81; 65, 82; 67, 83; 67, 84; 68, 85; 68, 86; 69, 87; 69, 88; 69, 89; 71, 90; 71, 91; 72, 92; 72, 93; 73, 94; 73, 95; 74, 96; 74, 97; 75, 98; 75, 99; 77, 100; 77, 101; 78, 102; 78, 103; 80, 104; 81, 105; 82, 106; 82, 107; 83, 108; 83, 109; 84, 110; 87, 111; 88, 112; 91, 113; 93, 114; 93, 115; 98, 116; 98, 117; 100, 118; 100, 119; 103, 120; 103, 121; 104, 122; 105, 123; 105, 124; 105, 125; 106, 126; 106, 127; 108, 128; 108, 129; 111, 130; 111, 131; 112, 132; 112, 133; 113, 134; 113, 135; 115, 136; 118, 137; 118, 138; 122, 139; 122, 140; 123, 141; 124, 142; 125, 143; 126, 144; 126, 145; 131, 146; 133, 147; 134, 148; 134, 149; 135, 150; 139, 151; 139, 152; 140, 153; 141, 154; 141, 155; 142, 156; 142, 157; 143, 158; 143, 159; 147, 160; 147, 161; 151, 162; 151, 163; 155, 164; 155, 165; 156, 166; 156, 167; 157, 168; 158, 169; 158, 170; 160, 171; 160, 172; 162, 173; 162, 174; 164, 175; 164, 176; 169, 177; 169, 178 | def poll_events(self):
"""Continuously polls all types of events from sl4a.
Events are sorted by name and store in separate queues.
If there are registered handlers, the handlers will be called with
corresponding event immediately upon event discovery, and the event
won't be stored. If exceptions occur, stop the dispatcher and return
"""
while self.started:
event_obj = None
event_name = None
try:
event_obj = self._sl4a.eventWait(50000)
except:
if self.started:
print("Exception happened during polling.")
print(traceback.format_exc())
raise
if not event_obj:
continue
elif 'name' not in event_obj:
print("Received Malformed event {}".format(event_obj))
continue
else:
event_name = event_obj['name']
# if handler registered, process event
if event_name in self.handlers:
self.handle_subscribed_event(event_obj, event_name)
if event_name == "EventDispatcherShutdown":
self._sl4a.closeSl4aSession()
break
else:
self.lock.acquire()
if event_name in self.event_dict: # otherwise, cache event
self.event_dict[event_name].put(event_obj)
else:
q = queue.Queue()
q.put(event_obj)
self.event_dict[event_name] = q
self.lock.release() |
0, module; 1, function_definition; 2, function_name:pop_events; 3, parameters; 4, block; 5, identifier:self; 6, identifier:regex_pattern; 7, identifier:timeout; 8, expression_statement; 9, if_statement; 10, expression_statement; 11, while_statement; 12, if_statement; 13, return_statement; 14, comment:"""Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
Results are sorted by timestamp in ascending order.
Args:
regex_pattern: The regular expression pattern that an event name
should match in order to be popped.
timeout: Number of seconds to wait for events in case no event
matching the condition exits when the function is called.
Returns:
Events whose names match a regex pattern.
Empty if none exist and the wait timed out.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
queue.Empty: Raised if no event was found before time out.
"""; 15, not_operator; 16, block; 17, assignment; 18, True; 19, comment:#TODO: fix the sleep loop; 20, block; 21, comparison_operator:len(results) == 0; 22, block; 23, call; 24, attribute; 25, raise_statement; 26, identifier:deadline; 27, binary_operator:time.time() + timeout; 28, expression_statement; 29, if_statement; 30, expression_statement; 31, call; 32, integer:0; 33, raise_statement; 34, identifier:sorted; 35, argument_list; 36, identifier:self; 37, identifier:started; 38, call; 39, call; 40, identifier:timeout; 41, assignment; 42, boolean_operator; 43, block; 44, call; 45, identifier:len; 46, argument_list; 47, call; 48, identifier:results; 49, keyword_argument; 50, identifier:IllegalStateError; 51, argument_list; 52, attribute; 53, argument_list; 54, identifier:results; 55, call; 56, comparison_operator:len(results) != 0; 57, comparison_operator:time.time() > deadline; 58, break_statement; 59, attribute; 60, argument_list; 61, identifier:results; 62, attribute; 63, argument_list; 64, identifier:key; 65, lambda; 66, string:"Dispatcher needs to be started before popping."; 67, identifier:time; 68, identifier:time; 69, attribute; 70, argument_list; 71, call; 72, integer:0; 73, call; 74, identifier:deadline; 75, identifier:time; 76, identifier:sleep; 77, integer:1; 78, identifier:queue; 79, identifier:Empty; 80, call; 81, lambda_parameters; 82, subscript; 83, identifier:self; 84, identifier:_match_and_pop; 85, identifier:regex_pattern; 86, identifier:len; 87, argument_list; 88, attribute; 89, argument_list; 90, attribute; 91, argument_list; 92, identifier:event; 93, identifier:event; 94, string; 95, identifier:results; 96, identifier:time; 97, identifier:time; 98, string; 99, identifier:format; 100, identifier:timeout; 101, identifier:regex_pattern; 102, string_content:time; 103, string_content:Timeout after {}s waiting for event: {} | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 8, 14; 9, 15; 9, 16; 10, 17; 11, 18; 11, 19; 11, 20; 12, 21; 12, 22; 13, 23; 15, 24; 16, 25; 17, 26; 17, 27; 20, 28; 20, 29; 20, 30; 21, 31; 21, 32; 22, 33; 23, 34; 23, 35; 24, 36; 24, 37; 25, 38; 27, 39; 27, 40; 28, 41; 29, 42; 29, 43; 30, 44; 31, 45; 31, 46; 33, 47; 35, 48; 35, 49; 38, 50; 38, 51; 39, 52; 39, 53; 41, 54; 41, 55; 42, 56; 42, 57; 43, 58; 44, 59; 44, 60; 46, 61; 47, 62; 47, 63; 49, 64; 49, 65; 51, 66; 52, 67; 52, 68; 55, 69; 55, 70; 56, 71; 56, 72; 57, 73; 57, 74; 59, 75; 59, 76; 60, 77; 62, 78; 62, 79; 63, 80; 65, 81; 65, 82; 69, 83; 69, 84; 70, 85; 71, 86; 71, 87; 73, 88; 73, 89; 80, 90; 80, 91; 81, 92; 82, 93; 82, 94; 87, 95; 88, 96; 88, 97; 90, 98; 90, 99; 91, 100; 91, 101; 94, 102; 98, 103 | def pop_events(self, regex_pattern, timeout):
"""Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
Results are sorted by timestamp in ascending order.
Args:
regex_pattern: The regular expression pattern that an event name
should match in order to be popped.
timeout: Number of seconds to wait for events in case no event
matching the condition exits when the function is called.
Returns:
Events whose names match a regex pattern.
Empty if none exist and the wait timed out.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
queue.Empty: Raised if no event was found before time out.
"""
if not self.started:
raise IllegalStateError(
"Dispatcher needs to be started before popping.")
deadline = time.time() + timeout
while True:
#TODO: fix the sleep loop
results = self._match_and_pop(regex_pattern)
if len(results) != 0 or time.time() > deadline:
break
time.sleep(1)
if len(results) == 0:
raise queue.Empty('Timeout after {}s waiting for event: {}'.format(
timeout, regex_pattern))
return sorted(results, key=lambda event: event['time']) |
0, module; 1, function_definition; 2, function_name:children; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, return_statement; 8, comment:"""
The list of child messages and actions sorted by task level, excluding the
start and end messages.
"""; 9, call; 10, identifier:pvector; 11, argument_list; 12, call; 13, identifier:sorted; 14, argument_list; 15, call; 16, keyword_argument; 17, attribute; 18, argument_list; 19, identifier:key; 20, lambda; 21, attribute; 22, identifier:values; 23, lambda_parameters; 24, attribute; 25, identifier:self; 26, identifier:_children; 27, identifier:m; 28, identifier:m; 29, identifier:task_level | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 9, 10; 9, 11; 11, 12; 12, 13; 12, 14; 14, 15; 14, 16; 15, 17; 15, 18; 16, 19; 16, 20; 17, 21; 17, 22; 20, 23; 20, 24; 21, 25; 21, 26; 23, 27; 24, 28; 24, 29 | def children(self):
"""
The list of child messages and actions sorted by task level, excluding the
start and end messages.
"""
return pvector(
sorted(self._children.values(), key=lambda m: m.task_level)) |
0, module; 1, function_definition; 2, function_name:_get_last_child_with_lineno; 3, parameters; 4, block; 5, identifier:node; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, comment:# The fields of ast.Call are in the wrong order.; 10, if_statement; 11, for_statement; 12, return_statement; 13, comment:"""
Return the last direct child of `node` that has a lineno attribute,
or None if `node` has no such children.
Almost all node._field lists are sorted by the order in which they
appear in source code. For some nodes however, we have to skip some
fields that either don't have line numbers (e.g., "ctx" and "names")
or that are in the wrong position (e.g., "decorator_list" and
"returns"). Then we choose the first field (i.e., the field with the
highest line number) that actually contains a node. If it contains a
list of nodes, we return the last one.
"""; 14, assignment; 15, assignment; 16, call; 17, block; 18, identifier:name; 19, call; 20, block; 21, None; 22, identifier:ignored_fields; 23, call; 24, identifier:fields; 25, attribute; 26, identifier:isinstance; 27, argument_list; 28, expression_statement; 29, identifier:reversed; 30, argument_list; 31, if_statement; 32, try_statement; 33, comment:# Ignore non-AST objects like "is_async", "level" and "nl".; 34, if_statement; 35, identifier:set; 36, argument_list; 37, identifier:node; 38, identifier:_fields; 39, identifier:node; 40, attribute; 41, assignment; 42, identifier:fields; 43, comparison_operator:name in ignored_fields; 44, block; 45, block; 46, except_clause; 47, call; 48, block; 49, elif_clause; 50, list; 51, identifier:ast; 52, identifier:Call; 53, identifier:fields; 54, tuple; 55, identifier:name; 56, identifier:ignored_fields; 57, continue_statement; 58, expression_statement; 59, identifier:AttributeError; 60, block; 61, identifier:isinstance; 62, argument_list; 63, return_statement; 64, boolean_operator; 65, block; 66, string; 67, string; 68, string; 69, string; 70, string; 71, string; 72, string; 73, string; 74, string; 75, assignment; 76, continue_statement; 77, identifier:last_field; 78, attribute; 79, identifier:last_field; 80, call; 81, identifier:last_field; 82, return_statement; 83, string_content:ctx; 84, string_content:decorator_list; 85, string_content:names; 86, string_content:returns; 87, string_content:func; 88, string_content:args; 89, string_content:starargs; 90, string_content:keywords; 91, string_content:kwargs; 92, identifier:last_field; 93, call; 94, identifier:ast; 95, identifier:AST; 96, identifier:isinstance; 97, argument_list; 98, subscript; 99, identifier:getattr; 100, argument_list; 101, identifier:last_field; 102, identifier:list; 103, identifier:last_field; 104, unary_operator; 105, identifier:node; 106, identifier:name; 107, integer:1 | 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; 10, 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; 19, 29; 19, 30; 20, 31; 20, 32; 20, 33; 20, 34; 23, 35; 23, 36; 25, 37; 25, 38; 27, 39; 27, 40; 28, 41; 30, 42; 31, 43; 31, 44; 32, 45; 32, 46; 34, 47; 34, 48; 34, 49; 36, 50; 40, 51; 40, 52; 41, 53; 41, 54; 43, 55; 43, 56; 44, 57; 45, 58; 46, 59; 46, 60; 47, 61; 47, 62; 48, 63; 49, 64; 49, 65; 50, 66; 50, 67; 50, 68; 50, 69; 54, 70; 54, 71; 54, 72; 54, 73; 54, 74; 58, 75; 60, 76; 62, 77; 62, 78; 63, 79; 64, 80; 64, 81; 65, 82; 66, 83; 67, 84; 68, 85; 69, 86; 70, 87; 71, 88; 72, 89; 73, 90; 74, 91; 75, 92; 75, 93; 78, 94; 78, 95; 80, 96; 80, 97; 82, 98; 93, 99; 93, 100; 97, 101; 97, 102; 98, 103; 98, 104; 100, 105; 100, 106; 104, 107 | def _get_last_child_with_lineno(node):
"""
Return the last direct child of `node` that has a lineno attribute,
or None if `node` has no such children.
Almost all node._field lists are sorted by the order in which they
appear in source code. For some nodes however, we have to skip some
fields that either don't have line numbers (e.g., "ctx" and "names")
or that are in the wrong position (e.g., "decorator_list" and
"returns"). Then we choose the first field (i.e., the field with the
highest line number) that actually contains a node. If it contains a
list of nodes, we return the last one.
"""
ignored_fields = set(['ctx', 'decorator_list', 'names', 'returns'])
fields = node._fields
# The fields of ast.Call are in the wrong order.
if isinstance(node, ast.Call):
fields = ('func', 'args', 'starargs', 'keywords', 'kwargs')
for name in reversed(fields):
if name in ignored_fields:
continue
try:
last_field = getattr(node, name)
except AttributeError:
continue
# Ignore non-AST objects like "is_async", "level" and "nl".
if isinstance(last_field, ast.AST):
return last_field
elif isinstance(last_field, list) and last_field:
return last_field[-1]
return None |
0, module; 1, function_definition; 2, function_name:get_patched_ast; 3, parameters; 4, block; 5, identifier:source; 6, default_parameter; 7, expression_statement; 8, return_statement; 9, identifier:sorted_children; 10, False; 11, comment:"""Adds ``region`` and ``sorted_children`` fields to nodes
Adds ``sorted_children`` field only if `sorted_children` is True.
"""; 12, call; 13, identifier:patch_ast; 14, argument_list; 15, call; 16, identifier:source; 17, identifier:sorted_children; 18, attribute; 19, argument_list; 20, identifier:ast; 21, identifier:parse; 22, identifier:source | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 6, 9; 6, 10; 7, 11; 8, 12; 12, 13; 12, 14; 14, 15; 14, 16; 14, 17; 15, 18; 15, 19; 18, 20; 18, 21; 19, 22 | def get_patched_ast(source, sorted_children=False):
"""Adds ``region`` and ``sorted_children`` fields to nodes
Adds ``sorted_children`` field only if `sorted_children` is True.
"""
return patch_ast(ast.parse(source), source, sorted_children) |
0, module; 1, function_definition; 2, function_name:patch_ast; 3, parameters; 4, block; 5, identifier:node; 6, identifier:source; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, identifier:sorted_children; 14, False; 15, comment:"""Patches the given node
After calling, each node in `node` will have a new field named
`region` that is a tuple containing the start and end offsets
of the code that generated it.
If `sorted_children` is true, a `sorted_children` field will
be created for each node, too. It is a list containing child
nodes as well as whitespaces and comments that occur between
them.
"""; 16, call; 17, block; 18, assignment; 19, call; 20, identifier:node; 21, identifier:hasattr; 22, argument_list; 23, return_statement; 24, identifier:walker; 25, call; 26, attribute; 27, argument_list; 28, identifier:node; 29, string; 30, identifier:node; 31, identifier:_PatchingASTWalker; 32, argument_list; 33, identifier:ast; 34, identifier:call_for_nodes; 35, identifier:node; 36, identifier:walker; 37, string_content:region; 38, identifier:source; 39, keyword_argument; 40, identifier:children; 41, identifier:sorted_children | 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; 9, 16; 9, 17; 10, 18; 11, 19; 12, 20; 16, 21; 16, 22; 17, 23; 18, 24; 18, 25; 19, 26; 19, 27; 22, 28; 22, 29; 23, 30; 25, 31; 25, 32; 26, 33; 26, 34; 27, 35; 27, 36; 29, 37; 32, 38; 32, 39; 39, 40; 39, 41 | def patch_ast(node, source, sorted_children=False):
"""Patches the given node
After calling, each node in `node` will have a new field named
`region` that is a tuple containing the start and end offsets
of the code that generated it.
If `sorted_children` is true, a `sorted_children` field will
be created for each node, too. It is a list containing child
nodes as well as whitespaces and comments that occur between
them.
"""
if hasattr(node, 'region'):
return node
walker = _PatchingASTWalker(source, children=sorted_children)
ast.call_for_nodes(node, walker)
return node |
0, module; 1, function_definition; 2, function_name:write_ast; 3, parameters; 4, block; 5, identifier:patched_ast_node; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, return_statement; 10, comment:"""Extract source form a patched AST node with `sorted_children` field
If the node is patched with sorted_children turned off you can use
`node_region` function for obtaining code using module source code.
"""; 11, assignment; 12, identifier:child; 13, attribute; 14, block; 15, call; 16, identifier:result; 17, list; 18, identifier:patched_ast_node; 19, identifier:sorted_children; 20, if_statement; 21, attribute; 22, argument_list; 23, call; 24, block; 25, else_clause; 26, string; 27, identifier:join; 28, identifier:result; 29, identifier:isinstance; 30, argument_list; 31, expression_statement; 32, block; 33, identifier:child; 34, attribute; 35, call; 36, expression_statement; 37, identifier:ast; 38, identifier:AST; 39, attribute; 40, argument_list; 41, call; 42, identifier:result; 43, identifier:append; 44, call; 45, attribute; 46, argument_list; 47, identifier:write_ast; 48, argument_list; 49, identifier:result; 50, identifier:append; 51, identifier:child; 52, identifier:child | 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; 13, 18; 13, 19; 14, 20; 15, 21; 15, 22; 20, 23; 20, 24; 20, 25; 21, 26; 21, 27; 22, 28; 23, 29; 23, 30; 24, 31; 25, 32; 30, 33; 30, 34; 31, 35; 32, 36; 34, 37; 34, 38; 35, 39; 35, 40; 36, 41; 39, 42; 39, 43; 40, 44; 41, 45; 41, 46; 44, 47; 44, 48; 45, 49; 45, 50; 46, 51; 48, 52 | def write_ast(patched_ast_node):
"""Extract source form a patched AST node with `sorted_children` field
If the node is patched with sorted_children turned off you can use
`node_region` function for obtaining code using module source code.
"""
result = []
for child in patched_ast_node.sorted_children:
if isinstance(child, ast.AST):
result.append(write_ast(child))
else:
result.append(child)
return ''.join(result) |
0, module; 1, function_definition; 2, function_name:sorted_proposals; 3, parameters; 4, block; 5, identifier:proposals; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, return_statement; 11, identifier:scopepref; 12, None; 13, identifier:typepref; 14, None; 15, comment:"""Sort a list of proposals
Return a sorted list of the given `CodeAssistProposal`\s.
`scopepref` can be a list of proposal scopes. Defaults to
``['parameter_keyword', 'local', 'global', 'imported',
'attribute', 'builtin', 'keyword']``.
`typepref` can be a list of proposal types. Defaults to
``['class', 'function', 'instance', 'module', None]``.
(`None` stands for completions with no type like keywords.)
"""; 16, assignment; 17, call; 18, identifier:sorter; 19, call; 20, attribute; 21, argument_list; 22, identifier:_ProposalSorter; 23, argument_list; 24, identifier:sorter; 25, identifier:get_sorted_proposal_list; 26, identifier:proposals; 27, identifier:scopepref; 28, identifier:typepref | 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; 10, 17; 16, 18; 16, 19; 17, 20; 17, 21; 19, 22; 19, 23; 20, 24; 20, 25; 23, 26; 23, 27; 23, 28 | def sorted_proposals(proposals, scopepref=None, typepref=None):
"""Sort a list of proposals
Return a sorted list of the given `CodeAssistProposal`\s.
`scopepref` can be a list of proposal scopes. Defaults to
``['parameter_keyword', 'local', 'global', 'imported',
'attribute', 'builtin', 'keyword']``.
`typepref` can be a list of proposal types. Defaults to
``['class', 'function', 'instance', 'module', None]``.
(`None` stands for completions with no type like keywords.)
"""
sorter = _ProposalSorter(proposals, scopepref, typepref)
return sorter.get_sorted_proposal_list() |
0, module; 1, function_definition; 2, function_name:get_sorted_proposal_list; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, for_statement; 9, expression_statement; 10, for_statement; 11, return_statement; 12, comment:"""Return a list of `CodeAssistProposal`"""; 13, assignment; 14, identifier:proposal; 15, attribute; 16, block; 17, assignment; 18, identifier:scope; 19, attribute; 20, block; 21, identifier:result; 22, identifier:proposals; 23, dictionary; 24, identifier:self; 25, identifier:proposals; 26, expression_statement; 27, identifier:result; 28, list; 29, identifier:self; 30, identifier:scopepref; 31, expression_statement; 32, expression_statement; 33, expression_statement; 34, expression_statement; 35, call; 36, assignment; 37, assignment; 38, call; 39, call; 40, attribute; 41, argument_list; 42, identifier:scope_proposals; 43, call; 44, identifier:scope_proposals; 45, list_comprehension; 46, attribute; 47, argument_list; 48, attribute; 49, argument_list; 50, call; 51, identifier:append; 52, identifier:proposal; 53, attribute; 54, argument_list; 55, identifier:proposal; 56, for_in_clause; 57, if_clause; 58, identifier:scope_proposals; 59, identifier:sort; 60, keyword_argument; 61, identifier:result; 62, identifier:extend; 63, identifier:scope_proposals; 64, attribute; 65, argument_list; 66, identifier:proposals; 67, identifier:get; 68, identifier:scope; 69, list; 70, identifier:proposal; 71, identifier:scope_proposals; 72, comparison_operator:proposal.type in self.typerank; 73, identifier:key; 74, attribute; 75, identifier:proposals; 76, identifier:setdefault; 77, attribute; 78, list; 79, attribute; 80, attribute; 81, identifier:self; 82, identifier:_proposal_key; 83, identifier:proposal; 84, identifier:scope; 85, identifier:proposal; 86, identifier:type; 87, identifier:self; 88, identifier:typerank | 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; 8, 15; 8, 16; 9, 17; 10, 18; 10, 19; 10, 20; 11, 21; 13, 22; 13, 23; 15, 24; 15, 25; 16, 26; 17, 27; 17, 28; 19, 29; 19, 30; 20, 31; 20, 32; 20, 33; 20, 34; 26, 35; 31, 36; 32, 37; 33, 38; 34, 39; 35, 40; 35, 41; 36, 42; 36, 43; 37, 44; 37, 45; 38, 46; 38, 47; 39, 48; 39, 49; 40, 50; 40, 51; 41, 52; 43, 53; 43, 54; 45, 55; 45, 56; 45, 57; 46, 58; 46, 59; 47, 60; 48, 61; 48, 62; 49, 63; 50, 64; 50, 65; 53, 66; 53, 67; 54, 68; 54, 69; 56, 70; 56, 71; 57, 72; 60, 73; 60, 74; 64, 75; 64, 76; 65, 77; 65, 78; 72, 79; 72, 80; 74, 81; 74, 82; 77, 83; 77, 84; 79, 85; 79, 86; 80, 87; 80, 88 | def get_sorted_proposal_list(self):
"""Return a list of `CodeAssistProposal`"""
proposals = {}
for proposal in self.proposals:
proposals.setdefault(proposal.scope, []).append(proposal)
result = []
for scope in self.scopepref:
scope_proposals = proposals.get(scope, [])
scope_proposals = [proposal for proposal in scope_proposals
if proposal.type in self.typerank]
scope_proposals.sort(key=self._proposal_key)
result.extend(scope_proposals)
return result |
0, module; 1, function_definition; 2, function_name:get_rank; 3, parameters; 4, block; 5, identifier:self; 6, identifier:entity; 7, identifier:criteria; 8, default_parameter; 9, expression_statement; 10, comment:# If entity is for instance 'person.household', we get the reference entity 'household' behind the projector; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, comment:# Matrix: the value in line i and column j is the value of criteria for the jth person of the ith entity; 17, expression_statement; 18, comment:# We double-argsort all lines of the matrix.; 19, comment:# Double-argsorting gets the rank of each value once sorted; 20, comment:# For instance, if x = [3,1,6,4,0], y = np.argsort(x) is [4, 1, 0, 3, 2] (because the value with index 4 is the smallest one, the value with index 1 the second smallest, etc.) and z = np.argsort(y) is [2, 1, 4, 3, 0], the rank of each value.; 21, expression_statement; 22, comment:# Build the result vector by taking for each person the value in the right line (corresponding to its household id) and the right column (corresponding to its position); 23, expression_statement; 24, comment:# Return -1 for the persons who don't respect the condition; 25, return_statement; 26, identifier:condition; 27, True; 28, comment:"""
Get the rank of a person within an entity according to a criteria.
The person with rank 0 has the minimum value of criteria.
If condition is specified, then the persons who don't respect it are not taken into account and their rank is -1.
Example:
>>> age = person('age', period) # e.g [32, 34, 2, 8, 1]
>>> person.get_rank(household, age)
>>> [3, 4, 0, 2, 1]
>>> is_child = person.has_role(Household.CHILD) # [False, False, True, True, True]
>>> person.get_rank(household, - age, condition = is_child) # Sort in reverse order so that the eldest child gets the rank 0.
>>> [-1, -1, 1, 0, 2]
"""; 29, assignment; 30, assignment; 31, assignment; 32, assignment; 33, assignment; 34, assignment; 35, assignment; 36, assignment; 37, call; 38, identifier:entity; 39, conditional_expression:entity if not isinstance(entity, Projector) else entity.reference_entity; 40, identifier:positions; 41, attribute; 42, identifier:biggest_entity_size; 43, binary_operator:np.max(positions) + 1; 44, identifier:filtered_criteria; 45, call; 46, identifier:ids; 47, attribute; 48, identifier:matrix; 49, call; 50, identifier:sorted_matrix; 51, call; 52, identifier:result; 53, subscript; 54, attribute; 55, argument_list; 56, identifier:entity; 57, not_operator; 58, attribute; 59, identifier:entity; 60, identifier:members_position; 61, call; 62, integer:1; 63, attribute; 64, argument_list; 65, identifier:entity; 66, identifier:members_entity_id; 67, attribute; 68, argument_list; 69, attribute; 70, argument_list; 71, identifier:sorted_matrix; 72, identifier:ids; 73, identifier:positions; 74, identifier:np; 75, identifier:where; 76, identifier:condition; 77, identifier:result; 78, unary_operator; 79, call; 80, identifier:entity; 81, identifier:reference_entity; 82, attribute; 83, argument_list; 84, identifier:np; 85, identifier:where; 86, identifier:condition; 87, identifier:criteria; 88, attribute; 89, call; 90, identifier:transpose; 91, identifier:np; 92, identifier:argsort; 93, call; 94, integer:1; 95, identifier:isinstance; 96, argument_list; 97, identifier:np; 98, identifier:max; 99, identifier:positions; 100, identifier:np; 101, identifier:inf; 102, attribute; 103, argument_list; 104, attribute; 105, argument_list; 106, identifier:entity; 107, identifier:Projector; 108, identifier:np; 109, identifier:asarray; 110, list_comprehension; 111, identifier:np; 112, identifier:argsort; 113, identifier:matrix; 114, call; 115, for_in_clause; 116, attribute; 117, argument_list; 118, identifier:k; 119, call; 120, identifier:entity; 121, identifier:value_nth_person; 122, identifier:k; 123, identifier:filtered_criteria; 124, keyword_argument; 125, identifier:range; 126, argument_list; 127, identifier:default; 128, attribute; 129, identifier:biggest_entity_size; 130, identifier:np; 131, identifier:inf | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 8, 26; 8, 27; 9, 28; 11, 29; 12, 30; 13, 31; 14, 32; 15, 33; 17, 34; 21, 35; 23, 36; 25, 37; 29, 38; 29, 39; 30, 40; 30, 41; 31, 42; 31, 43; 32, 44; 32, 45; 33, 46; 33, 47; 34, 48; 34, 49; 35, 50; 35, 51; 36, 52; 36, 53; 37, 54; 37, 55; 39, 56; 39, 57; 39, 58; 41, 59; 41, 60; 43, 61; 43, 62; 45, 63; 45, 64; 47, 65; 47, 66; 49, 67; 49, 68; 51, 69; 51, 70; 53, 71; 53, 72; 53, 73; 54, 74; 54, 75; 55, 76; 55, 77; 55, 78; 57, 79; 58, 80; 58, 81; 61, 82; 61, 83; 63, 84; 63, 85; 64, 86; 64, 87; 64, 88; 67, 89; 67, 90; 69, 91; 69, 92; 70, 93; 78, 94; 79, 95; 79, 96; 82, 97; 82, 98; 83, 99; 88, 100; 88, 101; 89, 102; 89, 103; 93, 104; 93, 105; 96, 106; 96, 107; 102, 108; 102, 109; 103, 110; 104, 111; 104, 112; 105, 113; 110, 114; 110, 115; 114, 116; 114, 117; 115, 118; 115, 119; 116, 120; 116, 121; 117, 122; 117, 123; 117, 124; 119, 125; 119, 126; 124, 127; 124, 128; 126, 129; 128, 130; 128, 131 | def get_rank(self, entity, criteria, condition = True):
"""
Get the rank of a person within an entity according to a criteria.
The person with rank 0 has the minimum value of criteria.
If condition is specified, then the persons who don't respect it are not taken into account and their rank is -1.
Example:
>>> age = person('age', period) # e.g [32, 34, 2, 8, 1]
>>> person.get_rank(household, age)
>>> [3, 4, 0, 2, 1]
>>> is_child = person.has_role(Household.CHILD) # [False, False, True, True, True]
>>> person.get_rank(household, - age, condition = is_child) # Sort in reverse order so that the eldest child gets the rank 0.
>>> [-1, -1, 1, 0, 2]
"""
# If entity is for instance 'person.household', we get the reference entity 'household' behind the projector
entity = entity if not isinstance(entity, Projector) else entity.reference_entity
positions = entity.members_position
biggest_entity_size = np.max(positions) + 1
filtered_criteria = np.where(condition, criteria, np.inf)
ids = entity.members_entity_id
# Matrix: the value in line i and column j is the value of criteria for the jth person of the ith entity
matrix = np.asarray([
entity.value_nth_person(k, filtered_criteria, default = np.inf)
for k in range(biggest_entity_size)
]).transpose()
# We double-argsort all lines of the matrix.
# Double-argsorting gets the rank of each value once sorted
# For instance, if x = [3,1,6,4,0], y = np.argsort(x) is [4, 1, 0, 3, 2] (because the value with index 4 is the smallest one, the value with index 1 the second smallest, etc.) and z = np.argsort(y) is [2, 1, 4, 3, 0], the rank of each value.
sorted_matrix = np.argsort(np.argsort(matrix))
# Build the result vector by taking for each person the value in the right line (corresponding to its household id) and the right column (corresponding to its position)
result = sorted_matrix[ids, positions]
# Return -1 for the persons who don't respect the condition
return np.where(condition, result, -1) |
0, module; 1, function_definition; 2, function_name:value_nth_person; 3, parameters; 4, block; 5, identifier:self; 6, identifier:n; 7, identifier:array; 8, default_parameter; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, comment:# For households that have at least n persons, set the result as the value of criteria for the person for which the position is n.; 16, comment:# The map is needed b/c the order of the nth persons of each household in the persons vector is not necessarily the same than the household order.; 17, expression_statement; 18, return_statement; 19, identifier:default; 20, integer:0; 21, comment:"""
Get the value of array for the person whose position in the entity is n.
Note that this position is arbitrary, and that members are not sorted.
If the nth person does not exist, return ``default`` instead.
The result is a vector which dimension is the number of entities.
"""; 22, call; 23, assignment; 24, assignment; 25, assignment; 26, assignment; 27, assignment; 28, identifier:result; 29, attribute; 30, argument_list; 31, identifier:positions; 32, attribute; 33, identifier:nb_persons_per_entity; 34, call; 35, identifier:members_map; 36, attribute; 37, identifier:result; 38, call; 39, subscript; 40, subscript; 41, attribute; 42, identifier:check_array_compatible_with_entity; 43, identifier:array; 44, identifier:self; 45, identifier:members_position; 46, attribute; 47, argument_list; 48, identifier:self; 49, identifier:ordered_members_map; 50, attribute; 51, argument_list; 52, identifier:result; 53, comparison_operator:nb_persons_per_entity > n; 54, subscript; 55, comparison_operator:positions[members_map] == n; 56, identifier:self; 57, identifier:members; 58, identifier:self; 59, identifier:nb_persons; 60, identifier:self; 61, identifier:filled_array; 62, identifier:default; 63, keyword_argument; 64, identifier:nb_persons_per_entity; 65, identifier:n; 66, identifier:array; 67, identifier:members_map; 68, subscript; 69, identifier:n; 70, identifier:dtype; 71, attribute; 72, identifier:positions; 73, identifier:members_map; 74, identifier:array; 75, identifier:dtype | 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; 8, 19; 8, 20; 9, 21; 10, 22; 11, 23; 12, 24; 13, 25; 14, 26; 17, 27; 18, 28; 22, 29; 22, 30; 23, 31; 23, 32; 24, 33; 24, 34; 25, 35; 25, 36; 26, 37; 26, 38; 27, 39; 27, 40; 29, 41; 29, 42; 30, 43; 32, 44; 32, 45; 34, 46; 34, 47; 36, 48; 36, 49; 38, 50; 38, 51; 39, 52; 39, 53; 40, 54; 40, 55; 41, 56; 41, 57; 46, 58; 46, 59; 50, 60; 50, 61; 51, 62; 51, 63; 53, 64; 53, 65; 54, 66; 54, 67; 55, 68; 55, 69; 63, 70; 63, 71; 68, 72; 68, 73; 71, 74; 71, 75 | def value_nth_person(self, n, array, default = 0):
"""
Get the value of array for the person whose position in the entity is n.
Note that this position is arbitrary, and that members are not sorted.
If the nth person does not exist, return ``default`` instead.
The result is a vector which dimension is the number of entities.
"""
self.members.check_array_compatible_with_entity(array)
positions = self.members_position
nb_persons_per_entity = self.nb_persons()
members_map = self.ordered_members_map
result = self.filled_array(default, dtype = array.dtype)
# For households that have at least n persons, set the result as the value of criteria for the person for which the position is n.
# The map is needed b/c the order of the nth persons of each household in the persons vector is not necessarily the same than the household order.
result[nb_persons_per_entity > n] = array[members_map][positions[members_map] == n]
return result |
0, module; 1, function_definition; 2, function_name:create_query_index; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, dictionary_splat_pattern; 11, expression_statement; 12, if_statement; 13, expression_statement; 14, return_statement; 15, identifier:design_document_id; 16, None; 17, identifier:index_name; 18, None; 19, identifier:index_type; 20, string; 21, identifier:partitioned; 22, False; 23, identifier:kwargs; 24, comment:"""
Creates either a JSON or a text query index in the remote database.
:param str index_type: The type of the index to create. Can
be either 'text' or 'json'. Defaults to 'json'.
:param str design_document_id: Optional identifier of the design
document in which the index will be created. If omitted the default
is that each index will be created in its own design document.
Indexes can be grouped into design documents for efficiency.
However, a change to one index in a design document will invalidate
all other indexes in the same document.
:param str index_name: Optional name of the index. If omitted, a name
will be generated automatically.
:param list fields: A list of fields that should be indexed. For JSON
indexes, the fields parameter is mandatory and should follow the
'sort syntax'. For example ``fields=['name', {'age': 'desc'}]``
will create an index on the 'name' field in ascending order and the
'age' field in descending order. For text indexes, the fields
parameter is optional. If it is included then each field element
in the fields list must be a single element dictionary where the
key is the field name and the value is the field type. For example
``fields=[{'name': 'string'}, {'age': 'number'}]``. Valid field
types are ``'string'``, ``'number'``, and ``'boolean'``.
:param dict default_field: Optional parameter that specifies how the
``$text`` operator can be used with the index. Only valid when
creating a text index.
:param dict selector: Optional parameter that can be used to limit the
index to a specific set of documents that match a query. It uses
the same syntax used for selectors in queries. Only valid when
creating a text index.
:returns: An Index object representing the index created in the
remote database
"""; 25, comparison_operator:index_type == JSON_INDEX_TYPE; 26, block; 27, elif_clause; 28, else_clause; 29, call; 30, identifier:index; 31, string_content:json; 32, identifier:index_type; 33, identifier:JSON_INDEX_TYPE; 34, expression_statement; 35, comparison_operator:index_type == TEXT_INDEX_TYPE; 36, block; 37, block; 38, attribute; 39, argument_list; 40, assignment; 41, identifier:index_type; 42, identifier:TEXT_INDEX_TYPE; 43, expression_statement; 44, raise_statement; 45, identifier:index; 46, identifier:create; 47, identifier:index; 48, call; 49, assignment; 50, call; 51, identifier:Index; 52, argument_list; 53, identifier:index; 54, call; 55, identifier:CloudantArgumentError; 56, argument_list; 57, identifier:self; 58, identifier:design_document_id; 59, identifier:index_name; 60, keyword_argument; 61, dictionary_splat; 62, identifier:TextIndex; 63, argument_list; 64, integer:103; 65, identifier:index_type; 66, identifier:partitioned; 67, identifier:partitioned; 68, identifier:kwargs; 69, identifier:self; 70, identifier:design_document_id; 71, identifier:index_name; 72, keyword_argument; 73, dictionary_splat; 74, identifier:partitioned; 75, identifier:partitioned; 76, identifier:kwargs | 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; 6, 15; 6, 16; 7, 17; 7, 18; 8, 19; 8, 20; 9, 21; 9, 22; 10, 23; 11, 24; 12, 25; 12, 26; 12, 27; 12, 28; 13, 29; 14, 30; 20, 31; 25, 32; 25, 33; 26, 34; 27, 35; 27, 36; 28, 37; 29, 38; 29, 39; 34, 40; 35, 41; 35, 42; 36, 43; 37, 44; 38, 45; 38, 46; 40, 47; 40, 48; 43, 49; 44, 50; 48, 51; 48, 52; 49, 53; 49, 54; 50, 55; 50, 56; 52, 57; 52, 58; 52, 59; 52, 60; 52, 61; 54, 62; 54, 63; 56, 64; 56, 65; 60, 66; 60, 67; 61, 68; 63, 69; 63, 70; 63, 71; 63, 72; 63, 73; 72, 74; 72, 75; 73, 76 | def create_query_index(
self,
design_document_id=None,
index_name=None,
index_type='json',
partitioned=False,
**kwargs
):
"""
Creates either a JSON or a text query index in the remote database.
:param str index_type: The type of the index to create. Can
be either 'text' or 'json'. Defaults to 'json'.
:param str design_document_id: Optional identifier of the design
document in which the index will be created. If omitted the default
is that each index will be created in its own design document.
Indexes can be grouped into design documents for efficiency.
However, a change to one index in a design document will invalidate
all other indexes in the same document.
:param str index_name: Optional name of the index. If omitted, a name
will be generated automatically.
:param list fields: A list of fields that should be indexed. For JSON
indexes, the fields parameter is mandatory and should follow the
'sort syntax'. For example ``fields=['name', {'age': 'desc'}]``
will create an index on the 'name' field in ascending order and the
'age' field in descending order. For text indexes, the fields
parameter is optional. If it is included then each field element
in the fields list must be a single element dictionary where the
key is the field name and the value is the field type. For example
``fields=[{'name': 'string'}, {'age': 'number'}]``. Valid field
types are ``'string'``, ``'number'``, and ``'boolean'``.
:param dict default_field: Optional parameter that specifies how the
``$text`` operator can be used with the index. Only valid when
creating a text index.
:param dict selector: Optional parameter that can be used to limit the
index to a specific set of documents that match a query. It uses
the same syntax used for selectors in queries. Only valid when
creating a text index.
:returns: An Index object representing the index created in the
remote database
"""
if index_type == JSON_INDEX_TYPE:
index = Index(self, design_document_id, index_name,
partitioned=partitioned, **kwargs)
elif index_type == TEXT_INDEX_TYPE:
index = TextIndex(self, design_document_id, index_name,
partitioned=partitioned, **kwargs)
else:
raise CloudantArgumentError(103, index_type)
index.create()
return index |
0, module; 1, function_definition; 2, function_name:get_search_result; 3, parameters; 4, block; 5, identifier:self; 6, identifier:ddoc_id; 7, identifier:index_name; 8, dictionary_splat_pattern; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, identifier:query_params; 13, comment:"""
Retrieves the raw JSON content from the remote database based on the
search index on the server, using the query_params provided as query
parameters. A ``query`` parameter containing the Lucene query
syntax is mandatory.
Example for search queries:
.. code-block:: python
# Assuming that 'searchindex001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve documents where the Lucene field name is 'name' and
# the value is 'julia*'
resp = db.get_search_result('ddoc001', 'searchindex001',
query='name:julia*',
include_docs=True)
for row in resp['rows']:
# Process search index data (in JSON format).
Example if the search query requires grouping by using
the ``group_field`` parameter:
.. code-block:: python
# Assuming that 'searchindex001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve JSON response content, limiting response to 10 documents
resp = db.get_search_result('ddoc001', 'searchindex001',
query='name:julia*',
group_field='name',
limit=10)
for group in resp['groups']:
for row in group['rows']:
# Process search index data (in JSON format).
:param str ddoc_id: Design document id used to get the search result.
:param str index_name: Name used in part to identify the index.
:param str bookmark: Optional string that enables you to specify which
page of results you require. Only valid for queries that do not
specify the ``group_field`` query parameter.
:param list counts: Optional JSON array of field names for which
counts should be produced. The response will contain counts for each
unique value of this field name among the documents matching the
search query.
Requires the index to have faceting enabled.
:param list drilldown: Optional list of fields that each define a
pair of a field name and a value. This field can be used several
times. The search will only match documents that have the given
value in the field name. It differs from using
``query=fieldname:value`` only in that the values are not analyzed.
:param str group_field: Optional string field by which to group
search matches. Fields containing other data
(numbers, objects, arrays) can not be used.
:param int group_limit: Optional number with the maximum group count.
This field can only be used if ``group_field`` query parameter
is specified.
:param group_sort: Optional JSON field that defines the order of the
groups in a search using ``group_field``. The default sort order
is relevance. This field can have the same values as the sort field,
so single fields as well as arrays of fields are supported.
:param int limit: Optional number to limit the maximum count of the
returned documents. In case of a grouped search, this parameter
limits the number of documents per group.
:param query/q: A Lucene query in the form of ``name:value``.
If name is omitted, the special value ``default`` is used.
The ``query`` parameter can be abbreviated as ``q``.
:param ranges: Optional JSON facet syntax that reuses the standard
Lucene syntax to return counts of results which fit into each
specified category. Inclusive range queries are denoted by brackets.
Exclusive range queries are denoted by curly brackets.
For example ``ranges={"price":{"cheap":"[0 TO 100]"}}`` has an
inclusive range of 0 to 100.
Requires the index to have faceting enabled.
:param sort: Optional JSON string of the form ``fieldname<type>`` for
ascending or ``-fieldname<type>`` for descending sort order.
Fieldname is the name of a string or number field and type is either
number or string or a JSON array of such strings. The type part is
optional and defaults to number.
:param str stale: Optional string to allow the results from a stale
index to be used. This makes the request return immediately, even
if the index has not been completely built yet.
:param list highlight_fields: Optional list of fields which should be
highlighted.
:param str highlight_pre_tag: Optional string inserted before the
highlighted word in the highlights output. Defaults to ``<em>``.
:param str highlight_post_tag: Optional string inserted after the
highlighted word in the highlights output. Defaults to ``</em>``.
:param int highlight_number: Optional number of fragments returned in
highlights. If the search term occurs less often than the number of
fragments specified, longer fragments are returned. Default is 1.
:param int highlight_size: Optional number of characters in each
fragment for highlights. Defaults to 100 characters.
:param list include_fields: Optional list of field names to include in
search results. Any fields included must have been indexed with the
``store:true`` option.
:returns: Search query result data in JSON format
"""; 14, assignment; 15, call; 16, identifier:ddoc; 17, call; 18, attribute; 19, argument_list; 20, identifier:DesignDocument; 21, argument_list; 22, identifier:self; 23, identifier:_get_search_result; 24, call; 25, dictionary_splat; 26, identifier:self; 27, identifier:ddoc_id; 28, attribute; 29, argument_list; 30, identifier:query_params; 31, string; 32, identifier:join; 33, tuple; 34, string_content:/; 35, attribute; 36, string; 37, identifier:index_name; 38, identifier:ddoc; 39, identifier:document_url; 40, string_content:_search | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 8, 12; 9, 13; 10, 14; 11, 15; 14, 16; 14, 17; 15, 18; 15, 19; 17, 20; 17, 21; 18, 22; 18, 23; 19, 24; 19, 25; 21, 26; 21, 27; 24, 28; 24, 29; 25, 30; 28, 31; 28, 32; 29, 33; 31, 34; 33, 35; 33, 36; 33, 37; 35, 38; 35, 39; 36, 40 | def get_search_result(self, ddoc_id, index_name, **query_params):
"""
Retrieves the raw JSON content from the remote database based on the
search index on the server, using the query_params provided as query
parameters. A ``query`` parameter containing the Lucene query
syntax is mandatory.
Example for search queries:
.. code-block:: python
# Assuming that 'searchindex001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve documents where the Lucene field name is 'name' and
# the value is 'julia*'
resp = db.get_search_result('ddoc001', 'searchindex001',
query='name:julia*',
include_docs=True)
for row in resp['rows']:
# Process search index data (in JSON format).
Example if the search query requires grouping by using
the ``group_field`` parameter:
.. code-block:: python
# Assuming that 'searchindex001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve JSON response content, limiting response to 10 documents
resp = db.get_search_result('ddoc001', 'searchindex001',
query='name:julia*',
group_field='name',
limit=10)
for group in resp['groups']:
for row in group['rows']:
# Process search index data (in JSON format).
:param str ddoc_id: Design document id used to get the search result.
:param str index_name: Name used in part to identify the index.
:param str bookmark: Optional string that enables you to specify which
page of results you require. Only valid for queries that do not
specify the ``group_field`` query parameter.
:param list counts: Optional JSON array of field names for which
counts should be produced. The response will contain counts for each
unique value of this field name among the documents matching the
search query.
Requires the index to have faceting enabled.
:param list drilldown: Optional list of fields that each define a
pair of a field name and a value. This field can be used several
times. The search will only match documents that have the given
value in the field name. It differs from using
``query=fieldname:value`` only in that the values are not analyzed.
:param str group_field: Optional string field by which to group
search matches. Fields containing other data
(numbers, objects, arrays) can not be used.
:param int group_limit: Optional number with the maximum group count.
This field can only be used if ``group_field`` query parameter
is specified.
:param group_sort: Optional JSON field that defines the order of the
groups in a search using ``group_field``. The default sort order
is relevance. This field can have the same values as the sort field,
so single fields as well as arrays of fields are supported.
:param int limit: Optional number to limit the maximum count of the
returned documents. In case of a grouped search, this parameter
limits the number of documents per group.
:param query/q: A Lucene query in the form of ``name:value``.
If name is omitted, the special value ``default`` is used.
The ``query`` parameter can be abbreviated as ``q``.
:param ranges: Optional JSON facet syntax that reuses the standard
Lucene syntax to return counts of results which fit into each
specified category. Inclusive range queries are denoted by brackets.
Exclusive range queries are denoted by curly brackets.
For example ``ranges={"price":{"cheap":"[0 TO 100]"}}`` has an
inclusive range of 0 to 100.
Requires the index to have faceting enabled.
:param sort: Optional JSON string of the form ``fieldname<type>`` for
ascending or ``-fieldname<type>`` for descending sort order.
Fieldname is the name of a string or number field and type is either
number or string or a JSON array of such strings. The type part is
optional and defaults to number.
:param str stale: Optional string to allow the results from a stale
index to be used. This makes the request return immediately, even
if the index has not been completely built yet.
:param list highlight_fields: Optional list of fields which should be
highlighted.
:param str highlight_pre_tag: Optional string inserted before the
highlighted word in the highlights output. Defaults to ``<em>``.
:param str highlight_post_tag: Optional string inserted after the
highlighted word in the highlights output. Defaults to ``</em>``.
:param int highlight_number: Optional number of fragments returned in
highlights. If the search term occurs less often than the number of
fragments specified, longer fragments are returned. Default is 1.
:param int highlight_size: Optional number of characters in each
fragment for highlights. Defaults to 100 characters.
:param list include_fields: Optional list of field names to include in
search results. Any fields included must have been indexed with the
``store:true`` option.
:returns: Search query result data in JSON format
"""
ddoc = DesignDocument(self, ddoc_id)
return self._get_search_result(
'/'.join((ddoc.document_url, '_search', index_name)),
**query_params
) |
0, module; 1, function_definition; 2, function_name:predict_log_proba; 3, parameters; 4, block; 5, identifier:self; 6, identifier:X; 7, expression_statement; 8, expression_statement; 9, comment:# normalize by P(x) = P(f_1, ..., f_n); 10, expression_statement; 11, comment:# return shape = (2,); 12, return_statement; 13, comment:"""
Return log-probability estimates for the test vector X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array-like, shape = [n_samples, n_classes]
Returns the log-probability of the samples for each class in
the model. The columns correspond to the classes in sorted
order, as they appear in the attribute `classes_`.
"""; 14, assignment; 15, assignment; 16, binary_operator:jll - np.atleast_2d(log_prob_x).T; 17, identifier:jll; 18, call; 19, identifier:log_prob_x; 20, call; 21, identifier:jll; 22, attribute; 23, attribute; 24, argument_list; 25, identifier:logsumexp; 26, argument_list; 27, call; 28, identifier:T; 29, identifier:self; 30, identifier:_joint_log_likelihood; 31, identifier:X; 32, identifier:jll; 33, keyword_argument; 34, attribute; 35, argument_list; 36, identifier:axis; 37, integer:1; 38, identifier:np; 39, identifier:atleast_2d; 40, identifier:log_prob_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; 7, 13; 8, 14; 10, 15; 12, 16; 14, 17; 14, 18; 15, 19; 15, 20; 16, 21; 16, 22; 18, 23; 18, 24; 20, 25; 20, 26; 22, 27; 22, 28; 23, 29; 23, 30; 24, 31; 26, 32; 26, 33; 27, 34; 27, 35; 33, 36; 33, 37; 34, 38; 34, 39; 35, 40 | def predict_log_proba(self, X):
"""
Return log-probability estimates for the test vector X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array-like, shape = [n_samples, n_classes]
Returns the log-probability of the samples for each class in
the model. The columns correspond to the classes in sorted
order, as they appear in the attribute `classes_`.
"""
jll = self._joint_log_likelihood(X)
# normalize by P(x) = P(f_1, ..., f_n)
log_prob_x = logsumexp(jll, axis=1) # return shape = (2,)
return jll - np.atleast_2d(log_prob_x).T |
0, module; 1, function_definition; 2, function_name:_get_sorting_key_values; 3, parameters; 4, block; 5, identifier:self; 6, identifier:array1; 7, identifier:array2; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, comment:"""return the sorting key values as a series"""; 13, assignment; 14, assignment; 15, call; 16, identifier:concat_arrays; 17, call; 18, identifier:unique_values; 19, call; 20, attribute; 21, argument_list; 22, attribute; 23, argument_list; 24, attribute; 25, argument_list; 26, identifier:numpy; 27, identifier:sort; 28, identifier:unique_values; 29, identifier:numpy; 30, identifier:concatenate; 31, list; 32, identifier:numpy; 33, identifier:unique; 34, identifier:concat_arrays; 35, identifier:array1; 36, identifier:array2 | 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; 11, 15; 13, 16; 13, 17; 14, 18; 14, 19; 15, 20; 15, 21; 17, 22; 17, 23; 19, 24; 19, 25; 20, 26; 20, 27; 21, 28; 22, 29; 22, 30; 23, 31; 24, 32; 24, 33; 25, 34; 31, 35; 31, 36 | def _get_sorting_key_values(self, array1, array2):
"""return the sorting key values as a series"""
concat_arrays = numpy.concatenate([array1, array2])
unique_values = numpy.unique(concat_arrays)
return numpy.sort(unique_values) |
0, module; 1, function_definition; 2, function_name:sortedneighbourhood; 3, parameters; 4, block; 5, identifier:self; 6, list_splat_pattern; 7, dictionary_splat_pattern; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, return_statement; 12, identifier:args; 13, identifier:kwargs; 14, comment:"""Add a Sorted Neighbourhood Index.
Shortcut of :class:`recordlinkage.index.SortedNeighbourhood`::
from recordlinkage.index import SortedNeighbourhood
indexer = recordlinkage.Index()
indexer.add(SortedNeighbourhood())
"""; 15, assignment; 16, call; 17, identifier:self; 18, identifier:indexer; 19, call; 20, attribute; 21, argument_list; 22, identifier:SortedNeighbourhood; 23, argument_list; 24, identifier:self; 25, identifier:add; 26, identifier:indexer; 27, list_splat; 28, dictionary_splat; 29, identifier:args; 30, identifier:kwargs | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 7, 13; 8, 14; 9, 15; 10, 16; 11, 17; 15, 18; 15, 19; 16, 20; 16, 21; 19, 22; 19, 23; 20, 24; 20, 25; 21, 26; 23, 27; 23, 28; 27, 29; 28, 30 | def sortedneighbourhood(self, *args, **kwargs):
"""Add a Sorted Neighbourhood Index.
Shortcut of :class:`recordlinkage.index.SortedNeighbourhood`::
from recordlinkage.index import SortedNeighbourhood
indexer = recordlinkage.Index()
indexer.add(SortedNeighbourhood())
"""
indexer = SortedNeighbourhood(*args, **kwargs)
self.add(indexer)
return self |
0, module; 1, function_definition; 2, function_name:_build_bst_from_sorted_values; 3, parameters; 4, block; 5, identifier:sorted_values; 6, expression_statement; 7, if_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, comment:"""Recursively build a perfect BST from odd number of sorted values.
:param sorted_values: Odd number of sorted values.
:type sorted_values: [int | float]
:return: Root node of the BST.
:rtype: binarytree.Node
"""; 14, comparison_operator:len(sorted_values) == 0; 15, block; 16, assignment; 17, assignment; 18, assignment; 19, assignment; 20, identifier:root; 21, call; 22, integer:0; 23, return_statement; 24, identifier:mid_index; 25, binary_operator:len(sorted_values) // 2; 26, identifier:root; 27, call; 28, attribute; 29, call; 30, attribute; 31, call; 32, identifier:len; 33, argument_list; 34, None; 35, call; 36, integer:2; 37, identifier:Node; 38, argument_list; 39, identifier:root; 40, identifier:left; 41, identifier:_build_bst_from_sorted_values; 42, argument_list; 43, identifier:root; 44, identifier:right; 45, identifier:_build_bst_from_sorted_values; 46, argument_list; 47, identifier:sorted_values; 48, identifier:len; 49, argument_list; 50, subscript; 51, subscript; 52, subscript; 53, identifier:sorted_values; 54, identifier:sorted_values; 55, identifier:mid_index; 56, identifier:sorted_values; 57, slice; 58, identifier:sorted_values; 59, slice; 60, identifier:mid_index; 61, binary_operator:mid_index + 1; 62, identifier:mid_index; 63, integer:1 | 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; 7, 15; 8, 16; 9, 17; 10, 18; 11, 19; 12, 20; 14, 21; 14, 22; 15, 23; 16, 24; 16, 25; 17, 26; 17, 27; 18, 28; 18, 29; 19, 30; 19, 31; 21, 32; 21, 33; 23, 34; 25, 35; 25, 36; 27, 37; 27, 38; 28, 39; 28, 40; 29, 41; 29, 42; 30, 43; 30, 44; 31, 45; 31, 46; 33, 47; 35, 48; 35, 49; 38, 50; 42, 51; 46, 52; 49, 53; 50, 54; 50, 55; 51, 56; 51, 57; 52, 58; 52, 59; 57, 60; 59, 61; 61, 62; 61, 63 | def _build_bst_from_sorted_values(sorted_values):
"""Recursively build a perfect BST from odd number of sorted values.
:param sorted_values: Odd number of sorted values.
:type sorted_values: [int | float]
:return: Root node of the BST.
:rtype: binarytree.Node
"""
if len(sorted_values) == 0:
return None
mid_index = len(sorted_values) // 2
root = Node(sorted_values[mid_index])
root.left = _build_bst_from_sorted_values(sorted_values[:mid_index])
root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:])
return root |
0, module; 1, function_definition; 2, function_name:holm; 3, parameters; 4, block; 5, identifier:pvals; 6, default_parameter; 7, expression_statement; 8, comment:# Convert to array and save original shape; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, comment:# Sort the (flattened) p-values; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, comment:# Now we adjust the p-values; 19, expression_statement; 20, expression_statement; 21, expression_statement; 22, comment:# And revert to the original shape and order; 23, expression_statement; 24, expression_statement; 25, with_statement; 26, return_statement; 27, identifier:alpha; 28, float:.05; 29, comment:"""P-values correction with Holm method.
Parameters
----------
pvals : array_like
Array of p-values of the individual tests.
alpha : float
Error rate (= alpha level).
Returns
-------
reject : array, bool
True if a hypothesis is rejected, False if not
pvals_corrected : array
P-values adjusted for multiple hypothesis testing using the Holm
procedure.
See also
--------
bonf : Bonferroni correction
fdr : Benjamini/Hochberg and Benjamini/Yekutieli FDR correction
Notes
-----
From Wikipedia:
In statistics, the Holm–Bonferroni method (also called the Holm method) is
used to counteract the problem of multiple comparisons. It is intended to
control the family-wise error rate and offers a simple test uniformly more
powerful than the Bonferroni correction.
The Holm adjusted p-values are the running maximum of the sorted p-values
divided by the corresponding increasing alpha level:
.. math::
\\frac{\\alpha}{n}, \\frac{\\alpha}{n-1}, ..., \\frac{\\alpha}{1}
where :math:`n` is the number of test.
The full mathematical formula is:
.. math::
\\widetilde {p}_{{(i)}}=\\max _{{j\\leq i}}\\left\\{(n-j+1)p_{{(j)}}
\\right\\}_{{1}}
Note that NaN values are not taken into account in the p-values correction.
References
----------
- Holm, S. (1979). A simple sequentially rejective multiple test procedure.
Scandinavian journal of statistics, 65-70.
- https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method
Examples
--------
>>> from pingouin import holm
>>> pvals = [.50, .003, .32, .054, .0003]
>>> reject, pvals_corr = holm(pvals, alpha=.05)
>>> print(reject, pvals_corr)
[False True False False True] [0.64 0.012 0.64 0.162 0.0015]
"""; 30, assignment; 31, assignment; 32, assignment; 33, assignment; 34, assignment; 35, assignment; 36, assignment; 37, assignment; 38, assignment; 39, assignment; 40, assignment; 41, assignment; 42, assignment; 43, with_clause; 44, block; 45, expression_list; 46, identifier:pvals; 47, call; 48, identifier:shape_init; 49, attribute; 50, identifier:pvals; 51, call; 52, identifier:num_nan; 53, call; 54, identifier:pvals_sortind; 55, call; 56, identifier:pvals_sorted; 57, subscript; 58, identifier:sortrevind; 59, call; 60, identifier:ntests; 61, binary_operator:pvals.size - num_nan; 62, identifier:pvals_corr; 63, call; 64, identifier:pvals_corr; 65, call; 66, identifier:pvals_corr; 67, call; 68, identifier:pvals_corr; 69, call; 70, identifier:pvals_corrected; 71, call; 72, with_item; 73, expression_statement; 74, identifier:reject; 75, identifier:pvals_corrected; 76, attribute; 77, argument_list; 78, identifier:pvals; 79, identifier:shape; 80, attribute; 81, argument_list; 82, attribute; 83, argument_list; 84, attribute; 85, argument_list; 86, identifier:pvals; 87, identifier:pvals_sortind; 88, attribute; 89, argument_list; 90, attribute; 91, identifier:num_nan; 92, attribute; 93, argument_list; 94, attribute; 95, argument_list; 96, attribute; 97, argument_list; 98, attribute; 99, argument_list; 100, attribute; 101, argument_list; 102, call; 103, assignment; 104, identifier:np; 105, identifier:asarray; 106, identifier:pvals; 107, identifier:pvals; 108, identifier:ravel; 109, call; 110, identifier:sum; 111, identifier:np; 112, identifier:argsort; 113, identifier:pvals; 114, identifier:pvals_sortind; 115, identifier:argsort; 116, identifier:pvals; 117, identifier:size; 118, identifier:np; 119, identifier:diag; 120, binary_operator:pvals_sorted * np.arange(ntests, 0, -1)[..., None]; 121, attribute; 122, identifier:accumulate; 123, identifier:pvals_corr; 124, identifier:np; 125, identifier:clip; 126, identifier:pvals_corr; 127, None; 128, integer:1; 129, identifier:np; 130, identifier:append; 131, identifier:pvals_corr; 132, call; 133, subscript; 134, identifier:reshape; 135, identifier:shape_init; 136, attribute; 137, argument_list; 138, identifier:reject; 139, call; 140, attribute; 141, argument_list; 142, identifier:pvals_sorted; 143, subscript; 144, identifier:np; 145, identifier:maximum; 146, attribute; 147, argument_list; 148, identifier:pvals_corr; 149, identifier:sortrevind; 150, identifier:np; 151, identifier:errstate; 152, keyword_argument; 153, attribute; 154, argument_list; 155, identifier:np; 156, identifier:isnan; 157, identifier:pvals; 158, call; 159, ellipsis:...; 160, None; 161, identifier:np; 162, identifier:full; 163, identifier:num_nan; 164, attribute; 165, identifier:invalid; 166, string; 167, identifier:np; 168, identifier:less; 169, identifier:pvals_corrected; 170, identifier:alpha; 171, attribute; 172, argument_list; 173, identifier:np; 174, identifier:nan; 175, string_content:ignore; 176, identifier:np; 177, identifier:arange; 178, identifier:ntests; 179, integer:0; 180, unary_operator; 181, integer:1 | 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; 6, 27; 6, 28; 7, 29; 9, 30; 10, 31; 11, 32; 12, 33; 14, 34; 15, 35; 16, 36; 17, 37; 19, 38; 20, 39; 21, 40; 23, 41; 24, 42; 25, 43; 25, 44; 26, 45; 30, 46; 30, 47; 31, 48; 31, 49; 32, 50; 32, 51; 33, 52; 33, 53; 34, 54; 34, 55; 35, 56; 35, 57; 36, 58; 36, 59; 37, 60; 37, 61; 38, 62; 38, 63; 39, 64; 39, 65; 40, 66; 40, 67; 41, 68; 41, 69; 42, 70; 42, 71; 43, 72; 44, 73; 45, 74; 45, 75; 47, 76; 47, 77; 49, 78; 49, 79; 51, 80; 51, 81; 53, 82; 53, 83; 55, 84; 55, 85; 57, 86; 57, 87; 59, 88; 59, 89; 61, 90; 61, 91; 63, 92; 63, 93; 65, 94; 65, 95; 67, 96; 67, 97; 69, 98; 69, 99; 71, 100; 71, 101; 72, 102; 73, 103; 76, 104; 76, 105; 77, 106; 80, 107; 80, 108; 82, 109; 82, 110; 84, 111; 84, 112; 85, 113; 88, 114; 88, 115; 90, 116; 90, 117; 92, 118; 92, 119; 93, 120; 94, 121; 94, 122; 95, 123; 96, 124; 96, 125; 97, 126; 97, 127; 97, 128; 98, 129; 98, 130; 99, 131; 99, 132; 100, 133; 100, 134; 101, 135; 102, 136; 102, 137; 103, 138; 103, 139; 109, 140; 109, 141; 120, 142; 120, 143; 121, 144; 121, 145; 132, 146; 132, 147; 133, 148; 133, 149; 136, 150; 136, 151; 137, 152; 139, 153; 139, 154; 140, 155; 140, 156; 141, 157; 143, 158; 143, 159; 143, 160; 146, 161; 146, 162; 147, 163; 147, 164; 152, 165; 152, 166; 153, 167; 153, 168; 154, 169; 154, 170; 158, 171; 158, 172; 164, 173; 164, 174; 166, 175; 171, 176; 171, 177; 172, 178; 172, 179; 172, 180; 180, 181 | def holm(pvals, alpha=.05):
"""P-values correction with Holm method.
Parameters
----------
pvals : array_like
Array of p-values of the individual tests.
alpha : float
Error rate (= alpha level).
Returns
-------
reject : array, bool
True if a hypothesis is rejected, False if not
pvals_corrected : array
P-values adjusted for multiple hypothesis testing using the Holm
procedure.
See also
--------
bonf : Bonferroni correction
fdr : Benjamini/Hochberg and Benjamini/Yekutieli FDR correction
Notes
-----
From Wikipedia:
In statistics, the Holm–Bonferroni method (also called the Holm method) is
used to counteract the problem of multiple comparisons. It is intended to
control the family-wise error rate and offers a simple test uniformly more
powerful than the Bonferroni correction.
The Holm adjusted p-values are the running maximum of the sorted p-values
divided by the corresponding increasing alpha level:
.. math::
\\frac{\\alpha}{n}, \\frac{\\alpha}{n-1}, ..., \\frac{\\alpha}{1}
where :math:`n` is the number of test.
The full mathematical formula is:
.. math::
\\widetilde {p}_{{(i)}}=\\max _{{j\\leq i}}\\left\\{(n-j+1)p_{{(j)}}
\\right\\}_{{1}}
Note that NaN values are not taken into account in the p-values correction.
References
----------
- Holm, S. (1979). A simple sequentially rejective multiple test procedure.
Scandinavian journal of statistics, 65-70.
- https://en.wikipedia.org/wiki/Holm%E2%80%93Bonferroni_method
Examples
--------
>>> from pingouin import holm
>>> pvals = [.50, .003, .32, .054, .0003]
>>> reject, pvals_corr = holm(pvals, alpha=.05)
>>> print(reject, pvals_corr)
[False True False False True] [0.64 0.012 0.64 0.162 0.0015]
"""
# Convert to array and save original shape
pvals = np.asarray(pvals)
shape_init = pvals.shape
pvals = pvals.ravel()
num_nan = np.isnan(pvals).sum()
# Sort the (flattened) p-values
pvals_sortind = np.argsort(pvals)
pvals_sorted = pvals[pvals_sortind]
sortrevind = pvals_sortind.argsort()
ntests = pvals.size - num_nan
# Now we adjust the p-values
pvals_corr = np.diag(pvals_sorted * np.arange(ntests, 0, -1)[..., None])
pvals_corr = np.maximum.accumulate(pvals_corr)
pvals_corr = np.clip(pvals_corr, None, 1)
# And revert to the original shape and order
pvals_corr = np.append(pvals_corr, np.full(num_nan, np.nan))
pvals_corrected = pvals_corr[sortrevind].reshape(shape_init)
with np.errstate(invalid='ignore'):
reject = np.less(pvals_corrected, alpha)
return reject, pvals_corrected |
0, module; 1, function_definition; 2, function_name:sort_reverse_chronologically; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, comment:"""
Sorts the measurements of this buffer in reverse chronological order
"""; 9, call; 10, attribute; 11, argument_list; 12, attribute; 13, identifier:sort; 14, keyword_argument; 15, keyword_argument; 16, identifier:self; 17, identifier:measurements; 18, identifier:key; 19, lambda; 20, identifier:reverse; 21, True; 22, lambda_parameters; 23, attribute; 24, identifier:m; 25, identifier:m; 26, identifier:timestamp | 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; 14, 18; 14, 19; 15, 20; 15, 21; 19, 22; 19, 23; 22, 24; 23, 25; 23, 26 | def sort_reverse_chronologically(self):
"""
Sorts the measurements of this buffer in reverse chronological order
"""
self.measurements.sort(key=lambda m: m.timestamp, reverse=True) |
0, module; 1, function_definition; 2, function_name:sorted_dependencies; 3, parameters; 4, block; 5, identifier:dist; 6, default_parameter; 7, expression_statement; 8, import_from_statement; 9, expression_statement; 10, comment:# create DAG as list of nodes and edges:; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, while_statement; 15, comment:# temporary stores used by depth first algorith.; 16, expression_statement; 17, expression_statement; 18, function_definition; 19, comment:# kickstart algorithm.; 20, while_statement; 21, if_statement; 22, return_statement; 23, identifier:reverse; 24, False; 25, comment:"""
Extract all underlying dependencies from a distribution sorted
topologically.
Uses depth-first algorithm. See more here:
Args:
dist (Dist):
Distribution to extract dependencies from.
reverse (bool):
If True, place dependencies in reverse order.
Returns:
dependencies (List[Dist]):
All distribution that ``dist`` is dependent on, sorted
topologically, including itself.
Examples:
>>> dist1 = chaospy.Uniform()
>>> dist2 = chaospy.Normal(dist1)
>>> print(sorted_dependencies(dist1))
[Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform()]
>>> print(sorted_dependencies(dist2)) # doctest: +NORMALIZE_WHITESPACE
[Normal(mu=Uniform(lower=0, upper=1), sigma=1),
Uniform(lower=0, upper=1),
Mul(uniform(), 0.5),
uniform(),
Mul(normal(), 1),
normal()]
>>> dist1 in sorted_dependencies(dist2)
True
>>> dist2 in sorted_dependencies(dist1)
False
Raises:
DependencyError:
If the dependency DAG is cyclic, dependency resolution is not
possible.
See also:
Depth-first algorithm section:
https://en.wikipedia.org/wiki/Topological_sorting
"""; 26, relative_import; 27, dotted_name; 28, assignment; 29, assignment; 30, assignment; 31, assignment; 32, identifier:pool; 33, block; 34, assignment; 35, assignment; 36, function_name:visit; 37, parameters; 38, block; 39, identifier:nodes; 40, block; 41, not_operator; 42, block; 43, identifier:pool; 44, import_prefix; 45, identifier:baseclass; 46, identifier:collection; 47, list; 48, identifier:nodes; 49, list; 50, identifier:edges; 51, list; 52, identifier:pool; 53, list; 54, expression_statement; 55, for_statement; 56, identifier:permanent_marks; 57, call; 58, identifier:temporary_marks; 59, call; 60, identifier:node; 61, expression_statement; 62, if_statement; 63, if_statement; 64, expression_statement; 65, expression_statement; 66, for_statement; 67, expression_statement; 68, expression_statement; 69, expression_statement; 70, expression_statement; 71, expression_statement; 72, identifier:reverse; 73, expression_statement; 74, identifier:dist; 75, identifier:dist; 76, identifier:dist; 77, assignment; 78, identifier:key; 79, call; 80, block; 81, identifier:set; 82, argument_list; 83, identifier:set; 84, argument_list; 85, comment:"""Depth-first topological sort algorithm."""; 86, comparison_operator:node in permanent_marks; 87, block; 88, comparison_operator:node in temporary_marks; 89, block; 90, call; 91, call; 92, pattern_list; 93, identifier:edges; 94, block; 95, call; 96, call; 97, call; 98, assignment; 99, call; 100, assignment; 101, identifier:dist; 102, call; 103, identifier:sorted; 104, argument_list; 105, expression_statement; 106, if_statement; 107, if_statement; 108, if_statement; 109, identifier:node; 110, identifier:permanent_marks; 111, return_statement; 112, identifier:node; 113, identifier:temporary_marks; 114, raise_statement; 115, attribute; 116, argument_list; 117, attribute; 118, argument_list; 119, identifier:node1; 120, identifier:node2; 121, if_statement; 122, attribute; 123, argument_list; 124, attribute; 125, argument_list; 126, attribute; 127, argument_list; 128, identifier:node; 129, subscript; 130, identifier:visit; 131, argument_list; 132, identifier:pool; 133, call; 134, attribute; 135, argument_list; 136, attribute; 137, assignment; 138, not_operator; 139, block; 140, comparison_operator:(dist, value) not in edges; 141, block; 142, comparison_operator:value not in nodes; 143, block; 144, call; 145, identifier:nodes; 146, identifier:remove; 147, identifier:node; 148, identifier:temporary_marks; 149, identifier:add; 150, identifier:node; 151, comparison_operator:node1 is node; 152, block; 153, identifier:temporary_marks; 154, identifier:remove; 155, identifier:node; 156, identifier:permanent_marks; 157, identifier:add; 158, identifier:node; 159, identifier:pool; 160, identifier:append; 161, identifier:node; 162, identifier:nodes; 163, integer:0; 164, identifier:node; 165, identifier:list; 166, argument_list; 167, identifier:pool; 168, identifier:pop; 169, identifier:dist; 170, identifier:prm; 171, identifier:value; 172, subscript; 173, call; 174, continue_statement; 175, tuple; 176, identifier:edges; 177, expression_statement; 178, identifier:value; 179, identifier:nodes; 180, expression_statement; 181, expression_statement; 182, identifier:DependencyError; 183, argument_list; 184, identifier:node1; 185, identifier:node; 186, expression_statement; 187, call; 188, attribute; 189, identifier:key; 190, identifier:isinstance; 191, argument_list; 192, identifier:dist; 193, identifier:value; 194, call; 195, call; 196, call; 197, string:"cycles in dependency structure."; 198, call; 199, identifier:reversed; 200, argument_list; 201, identifier:dist; 202, identifier:prm; 203, identifier:value; 204, attribute; 205, attribute; 206, argument_list; 207, attribute; 208, argument_list; 209, attribute; 210, argument_list; 211, identifier:visit; 212, argument_list; 213, identifier:pool; 214, identifier:baseclass; 215, identifier:Dist; 216, identifier:edges; 217, identifier:append; 218, tuple; 219, identifier:nodes; 220, identifier:append; 221, identifier:value; 222, identifier:pool; 223, identifier:append; 224, identifier:value; 225, identifier:node2; 226, identifier:dist; 227, identifier:value | 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; 6, 24; 7, 25; 8, 26; 8, 27; 9, 28; 11, 29; 12, 30; 13, 31; 14, 32; 14, 33; 16, 34; 17, 35; 18, 36; 18, 37; 18, 38; 20, 39; 20, 40; 21, 41; 21, 42; 22, 43; 26, 44; 27, 45; 28, 46; 28, 47; 29, 48; 29, 49; 30, 50; 30, 51; 31, 52; 31, 53; 33, 54; 33, 55; 34, 56; 34, 57; 35, 58; 35, 59; 37, 60; 38, 61; 38, 62; 38, 63; 38, 64; 38, 65; 38, 66; 38, 67; 38, 68; 38, 69; 40, 70; 40, 71; 41, 72; 42, 73; 47, 74; 49, 75; 53, 76; 54, 77; 55, 78; 55, 79; 55, 80; 57, 81; 57, 82; 59, 83; 59, 84; 61, 85; 62, 86; 62, 87; 63, 88; 63, 89; 64, 90; 65, 91; 66, 92; 66, 93; 66, 94; 67, 95; 68, 96; 69, 97; 70, 98; 71, 99; 73, 100; 77, 101; 77, 102; 79, 103; 79, 104; 80, 105; 80, 106; 80, 107; 80, 108; 86, 109; 86, 110; 87, 111; 88, 112; 88, 113; 89, 114; 90, 115; 90, 116; 91, 117; 91, 118; 92, 119; 92, 120; 94, 121; 95, 122; 95, 123; 96, 124; 96, 125; 97, 126; 97, 127; 98, 128; 98, 129; 99, 130; 99, 131; 100, 132; 100, 133; 102, 134; 102, 135; 104, 136; 105, 137; 106, 138; 106, 139; 107, 140; 107, 141; 108, 142; 108, 143; 114, 144; 115, 145; 115, 146; 116, 147; 117, 148; 117, 149; 118, 150; 121, 151; 121, 152; 122, 153; 122, 154; 123, 155; 124, 156; 124, 157; 125, 158; 126, 159; 126, 160; 127, 161; 129, 162; 129, 163; 131, 164; 133, 165; 133, 166; 134, 167; 134, 168; 136, 169; 136, 170; 137, 171; 137, 172; 138, 173; 139, 174; 140, 175; 140, 176; 141, 177; 142, 178; 142, 179; 143, 180; 143, 181; 144, 182; 144, 183; 151, 184; 151, 185; 152, 186; 166, 187; 172, 188; 172, 189; 173, 190; 173, 191; 175, 192; 175, 193; 177, 194; 180, 195; 181, 196; 183, 197; 186, 198; 187, 199; 187, 200; 188, 201; 188, 202; 191, 203; 191, 204; 194, 205; 194, 206; 195, 207; 195, 208; 196, 209; 196, 210; 198, 211; 198, 212; 200, 213; 204, 214; 204, 215; 205, 216; 205, 217; 206, 218; 207, 219; 207, 220; 208, 221; 209, 222; 209, 223; 210, 224; 212, 225; 218, 226; 218, 227 | def sorted_dependencies(dist, reverse=False):
"""
Extract all underlying dependencies from a distribution sorted
topologically.
Uses depth-first algorithm. See more here:
Args:
dist (Dist):
Distribution to extract dependencies from.
reverse (bool):
If True, place dependencies in reverse order.
Returns:
dependencies (List[Dist]):
All distribution that ``dist`` is dependent on, sorted
topologically, including itself.
Examples:
>>> dist1 = chaospy.Uniform()
>>> dist2 = chaospy.Normal(dist1)
>>> print(sorted_dependencies(dist1))
[Uniform(lower=0, upper=1), Mul(uniform(), 0.5), uniform()]
>>> print(sorted_dependencies(dist2)) # doctest: +NORMALIZE_WHITESPACE
[Normal(mu=Uniform(lower=0, upper=1), sigma=1),
Uniform(lower=0, upper=1),
Mul(uniform(), 0.5),
uniform(),
Mul(normal(), 1),
normal()]
>>> dist1 in sorted_dependencies(dist2)
True
>>> dist2 in sorted_dependencies(dist1)
False
Raises:
DependencyError:
If the dependency DAG is cyclic, dependency resolution is not
possible.
See also:
Depth-first algorithm section:
https://en.wikipedia.org/wiki/Topological_sorting
"""
from .. import baseclass
collection = [dist]
# create DAG as list of nodes and edges:
nodes = [dist]
edges = []
pool = [dist]
while pool:
dist = pool.pop()
for key in sorted(dist.prm):
value = dist.prm[key]
if not isinstance(value, baseclass.Dist):
continue
if (dist, value) not in edges:
edges.append((dist, value))
if value not in nodes:
nodes.append(value)
pool.append(value)
# temporary stores used by depth first algorith.
permanent_marks = set()
temporary_marks = set()
def visit(node):
"""Depth-first topological sort algorithm."""
if node in permanent_marks:
return
if node in temporary_marks:
raise DependencyError("cycles in dependency structure.")
nodes.remove(node)
temporary_marks.add(node)
for node1, node2 in edges:
if node1 is node:
visit(node2)
temporary_marks.remove(node)
permanent_marks.add(node)
pool.append(node)
# kickstart algorithm.
while nodes:
node = nodes[0]
visit(node)
if not reverse:
pool = list(reversed(pool))
return pool |
0, module; 1, function_definition; 2, function_name:orth_ttr; 3, parameters; 4, block; 5, identifier:order; 6, identifier:dist; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, dictionary_splat_pattern; 12, expression_statement; 13, expression_statement; 14, if_statement; 15, expression_statement; 16, if_statement; 17, expression_statement; 18, if_statement; 19, return_statement; 20, identifier:normed; 21, False; 22, identifier:sort; 23, string:"GR"; 24, identifier:retall; 25, False; 26, identifier:cross_truncation; 27, float:1.; 28, identifier:kws; 29, comment:"""
Create orthogonal polynomial expansion from three terms recursion formula.
Args:
order (int):
Order of polynomial expansion.
dist (Dist):
Distribution space where polynomials are orthogonal If dist.ttr
exists, it will be used. Must be stochastically independent.
normed (bool):
If True orthonormal polynomials will be used.
sort (str):
Polynomial sorting. Same as in basis.
retall (bool):
If true return numerical stabilized norms as well. Roughly the same
as ``cp.E(orth**2, dist)``.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion. only include terms where the exponents ``K``
satisfied the equation
``order >= sum(K**(1/cross_truncation))**cross_truncation``.
Returns:
(Poly, numpy.ndarray):
Orthogonal polynomial expansion and norms of the orthogonal
expansion on the form ``E(orth**2, dist)``. Calculated using
recurrence coefficients for stability.
Examples:
>>> Z = chaospy.Normal()
>>> print(chaospy.around(chaospy.orth_ttr(4, Z), 4))
[1.0, q0, q0^2-1.0, q0^3-3.0q0, q0^4-6.0q0^2+3.0]
"""; 30, assignment; 31, identifier:normed; 32, block; 33, assignment; 34, comparison_operator:dim > 1; 35, block; 36, else_clause; 37, assignment; 38, identifier:retall; 39, block; 40, identifier:polynomials; 41, pattern_list; 42, call; 43, for_statement; 44, expression_statement; 45, identifier:dim; 46, call; 47, identifier:dim; 48, integer:1; 49, expression_statement; 50, expression_statement; 51, expression_statement; 52, for_statement; 53, if_statement; 54, block; 55, identifier:polynomials; 56, call; 57, return_statement; 58, identifier:polynomials; 59, identifier:norms; 60, identifier:_; 61, identifier:_; 62, attribute; 63, argument_list; 64, pattern_list; 65, call; 66, block; 67, assignment; 68, identifier:len; 69, argument_list; 70, assignment; 71, assignment; 72, assignment; 73, identifier:index; 74, identifier:indices; 75, block; 76, identifier:retall; 77, block; 78, expression_statement; 79, expression_statement; 80, attribute; 81, argument_list; 82, expression_list; 83, attribute; 84, identifier:generate_stieltjes; 85, keyword_argument; 86, keyword_argument; 87, keyword_argument; 88, dictionary_splat; 89, identifier:idx; 90, identifier:poly; 91, identifier:enumerate; 92, argument_list; 93, expression_statement; 94, identifier:norms; 95, binary_operator:norms**0; 96, identifier:dist; 97, identifier:mv_polynomials; 98, list; 99, identifier:mv_norms; 100, list; 101, identifier:indices; 102, call; 103, expression_statement; 104, for_statement; 105, expression_statement; 106, for_statement; 107, assignment; 108, assignment; 109, attribute; 110, identifier:flatten; 111, call; 112, identifier:polynomials; 113, call; 114, identifier:chaospy; 115, identifier:quad; 116, identifier:dist; 117, identifier:dist; 118, identifier:order; 119, call; 120, identifier:retall; 121, True; 122, identifier:kws; 123, identifier:polynomials; 124, assignment; 125, identifier:norms; 126, integer:0; 127, attribute; 128, argument_list; 129, assignment; 130, identifier:idx; 131, call; 132, block; 133, call; 134, identifier:index; 135, identifier:indices; 136, block; 137, identifier:mv_norms; 138, subscript; 139, identifier:mv_polynomials; 140, identifier:polynomials; 141, identifier:chaospy; 142, identifier:poly; 143, attribute; 144, argument_list; 145, attribute; 146, argument_list; 147, attribute; 148, argument_list; 149, subscript; 150, binary_operator:poly / numpy.sqrt(norms[:, idx]); 151, attribute; 152, identifier:bindex; 153, keyword_argument; 154, keyword_argument; 155, keyword_argument; 156, keyword_argument; 157, keyword_argument; 158, identifier:poly; 159, subscript; 160, identifier:range; 161, argument_list; 162, expression_statement; 163, attribute; 164, argument_list; 165, expression_statement; 166, identifier:norms; 167, integer:0; 168, attribute; 169, identifier:Poly; 170, identifier:mv_polynomials; 171, identifier:numpy; 172, identifier:array; 173, identifier:mv_norms; 174, identifier:numpy; 175, identifier:max; 176, identifier:order; 177, identifier:polynomials; 178, identifier:idx; 179, identifier:poly; 180, call; 181, identifier:chaospy; 182, identifier:bertran; 183, identifier:start; 184, integer:0; 185, identifier:stop; 186, identifier:order; 187, identifier:dim; 188, identifier:dim; 189, identifier:sort; 190, identifier:sort; 191, identifier:cross_truncation; 192, identifier:cross_truncation; 193, subscript; 194, integer:0; 195, integer:1; 196, identifier:dim; 197, assignment; 198, identifier:mv_polynomials; 199, identifier:append; 200, identifier:poly; 201, call; 202, identifier:chaospy; 203, identifier:poly; 204, attribute; 205, argument_list; 206, identifier:polynomials; 207, subscript; 208, identifier:poly; 209, binary_operator:poly * polynomials[index[idx]][idx]; 210, attribute; 211, argument_list; 212, identifier:numpy; 213, identifier:sqrt; 214, subscript; 215, identifier:index; 216, integer:0; 217, identifier:poly; 218, subscript; 219, identifier:mv_norms; 220, identifier:append; 221, call; 222, identifier:norms; 223, slice; 224, identifier:idx; 225, subscript; 226, identifier:idx; 227, attribute; 228, argument_list; 229, identifier:polynomials; 230, subscript; 231, identifier:numpy; 232, identifier:prod; 233, list_comprehension; 234, identifier:index; 235, identifier:idx; 236, subscript; 237, for_in_clause; 238, identifier:norms; 239, identifier:idx; 240, subscript; 241, identifier:idx; 242, call; 243, identifier:index; 244, identifier:idx; 245, identifier:range; 246, argument_list; 247, identifier:dim | 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; 7, 20; 7, 21; 8, 22; 8, 23; 9, 24; 9, 25; 10, 26; 10, 27; 11, 28; 12, 29; 13, 30; 14, 31; 14, 32; 15, 33; 16, 34; 16, 35; 16, 36; 17, 37; 18, 38; 18, 39; 19, 40; 30, 41; 30, 42; 32, 43; 32, 44; 33, 45; 33, 46; 34, 47; 34, 48; 35, 49; 35, 50; 35, 51; 35, 52; 35, 53; 36, 54; 37, 55; 37, 56; 39, 57; 41, 58; 41, 59; 41, 60; 41, 61; 42, 62; 42, 63; 43, 64; 43, 65; 43, 66; 44, 67; 46, 68; 46, 69; 49, 70; 50, 71; 51, 72; 52, 73; 52, 74; 52, 75; 53, 76; 53, 77; 54, 78; 54, 79; 56, 80; 56, 81; 57, 82; 62, 83; 62, 84; 63, 85; 63, 86; 63, 87; 63, 88; 64, 89; 64, 90; 65, 91; 65, 92; 66, 93; 67, 94; 67, 95; 69, 96; 70, 97; 70, 98; 71, 99; 71, 100; 72, 101; 72, 102; 75, 103; 75, 104; 75, 105; 77, 106; 78, 107; 79, 108; 80, 109; 80, 110; 81, 111; 82, 112; 82, 113; 83, 114; 83, 115; 85, 116; 85, 117; 86, 118; 86, 119; 87, 120; 87, 121; 88, 122; 92, 123; 93, 124; 95, 125; 95, 126; 102, 127; 102, 128; 103, 129; 104, 130; 104, 131; 104, 132; 105, 133; 106, 134; 106, 135; 106, 136; 107, 137; 107, 138; 108, 139; 108, 140; 109, 141; 109, 142; 111, 143; 111, 144; 113, 145; 113, 146; 119, 147; 119, 148; 124, 149; 124, 150; 127, 151; 127, 152; 128, 153; 128, 154; 128, 155; 128, 156; 128, 157; 129, 158; 129, 159; 131, 160; 131, 161; 132, 162; 133, 163; 133, 164; 136, 165; 138, 166; 138, 167; 143, 168; 143, 169; 144, 170; 145, 171; 145, 172; 146, 173; 147, 174; 147, 175; 148, 176; 149, 177; 149, 178; 150, 179; 150, 180; 151, 181; 151, 182; 153, 183; 153, 184; 154, 185; 154, 186; 155, 187; 155, 188; 156, 189; 156, 190; 157, 191; 157, 192; 159, 193; 159, 194; 161, 195; 161, 196; 162, 197; 163, 198; 163, 199; 164, 200; 165, 201; 168, 202; 168, 203; 180, 204; 180, 205; 193, 206; 193, 207; 197, 208; 197, 209; 201, 210; 201, 211; 204, 212; 204, 213; 205, 214; 207, 215; 207, 216; 209, 217; 209, 218; 210, 219; 210, 220; 211, 221; 214, 222; 214, 223; 214, 224; 218, 225; 218, 226; 221, 227; 221, 228; 225, 229; 225, 230; 227, 231; 227, 232; 228, 233; 230, 234; 230, 235; 233, 236; 233, 237; 236, 238; 236, 239; 236, 240; 237, 241; 237, 242; 240, 243; 240, 244; 242, 245; 242, 246; 246, 247 | def orth_ttr(
order, dist, normed=False, sort="GR", retall=False,
cross_truncation=1., **kws):
"""
Create orthogonal polynomial expansion from three terms recursion formula.
Args:
order (int):
Order of polynomial expansion.
dist (Dist):
Distribution space where polynomials are orthogonal If dist.ttr
exists, it will be used. Must be stochastically independent.
normed (bool):
If True orthonormal polynomials will be used.
sort (str):
Polynomial sorting. Same as in basis.
retall (bool):
If true return numerical stabilized norms as well. Roughly the same
as ``cp.E(orth**2, dist)``.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion. only include terms where the exponents ``K``
satisfied the equation
``order >= sum(K**(1/cross_truncation))**cross_truncation``.
Returns:
(Poly, numpy.ndarray):
Orthogonal polynomial expansion and norms of the orthogonal
expansion on the form ``E(orth**2, dist)``. Calculated using
recurrence coefficients for stability.
Examples:
>>> Z = chaospy.Normal()
>>> print(chaospy.around(chaospy.orth_ttr(4, Z), 4))
[1.0, q0, q0^2-1.0, q0^3-3.0q0, q0^4-6.0q0^2+3.0]
"""
polynomials, norms, _, _ = chaospy.quad.generate_stieltjes(
dist=dist, order=numpy.max(order), retall=True, **kws)
if normed:
for idx, poly in enumerate(polynomials):
polynomials[idx] = poly / numpy.sqrt(norms[:, idx])
norms = norms**0
dim = len(dist)
if dim > 1:
mv_polynomials = []
mv_norms = []
indices = chaospy.bertran.bindex(
start=0, stop=order, dim=dim, sort=sort,
cross_truncation=cross_truncation,
)
for index in indices:
poly = polynomials[index[0]][0]
for idx in range(1, dim):
poly = poly * polynomials[index[idx]][idx]
mv_polynomials.append(poly)
if retall:
for index in indices:
mv_norms.append(
numpy.prod([norms[idx, index[idx]] for idx in range(dim)]))
else:
mv_norms = norms[0]
mv_polynomials = polynomials
polynomials = chaospy.poly.flatten(chaospy.poly.Poly(mv_polynomials))
if retall:
return polynomials, numpy.array(mv_norms)
return polynomials |
0, module; 1, function_definition; 2, function_name:orth_chol; 3, parameters; 4, block; 5, identifier:order; 6, identifier:dist; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, dictionary_splat_pattern; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, if_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, expression_statement; 22, expression_statement; 23, expression_statement; 24, expression_statement; 25, expression_statement; 26, expression_statement; 27, for_statement; 28, expression_statement; 29, return_statement; 30, identifier:normed; 31, True; 32, identifier:sort; 33, string:"GR"; 34, identifier:cross_truncation; 35, float:1.; 36, identifier:kws; 37, comment:"""
Create orthogonal polynomial expansion from Cholesky decomposition.
Args:
order (int):
Order of polynomial expansion
dist (Dist):
Distribution space where polynomials are orthogonal
normed (bool):
If True orthonormal polynomials will be used instead of monic.
sort (str):
Ordering argument passed to poly.basis. If custom basis is used,
argument is ignored.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Examples:
>>> Z = chaospy.Normal()
>>> print(chaospy.around(chaospy.orth_chol(3, Z), 4))
[1.0, q0, 0.7071q0^2-0.7071, 0.4082q0^3-1.2247q0]
"""; 38, assignment; 39, assignment; 40, assignment; 41, assignment; 42, assignment; 43, not_operator; 44, block; 45, assignment; 46, assignment; 47, assignment; 48, assignment; 49, assignment; 50, assignment; 51, assignment; 52, assignment; 53, assignment; 54, identifier:idx; 55, call; 56, block; 57, assignment; 58, identifier:polynomials; 59, identifier:dim; 60, call; 61, identifier:basis; 62, call; 63, identifier:length; 64, call; 65, identifier:cholmat; 66, call; 67, identifier:cholmat_inv; 68, attribute; 69, identifier:normed; 70, expression_statement; 71, expression_statement; 72, identifier:coefs; 73, call; 74, subscript; 75, identifier:cholmat_inv; 76, subscript; 77, integer:1; 78, subscript; 79, integer:0; 80, identifier:expected; 81, unary_operator; 82, subscript; 83, identifier:expected; 84, identifier:coefs; 85, attribute; 86, identifier:out; 87, dictionary; 88, subscript; 89, subscript; 90, identifier:range; 91, argument_list; 92, expression_statement; 93, expression_statement; 94, identifier:polynomials; 95, call; 96, identifier:len; 97, argument_list; 98, attribute; 99, argument_list; 100, identifier:len; 101, argument_list; 102, attribute; 103, argument_list; 104, call; 105, identifier:T; 106, assignment; 107, augmented_assignment; 108, attribute; 109, argument_list; 110, identifier:coefs; 111, slice; 112, slice; 113, identifier:coefs; 114, integer:0; 115, integer:0; 116, identifier:coefs; 117, integer:0; 118, slice; 119, call; 120, identifier:coefs; 121, slice; 122, integer:0; 123, identifier:coefs; 124, identifier:T; 125, identifier:out; 126, binary_operator:(0,)*dim; 127, identifier:coefs; 128, integer:0; 129, identifier:length; 130, assignment; 131, assignment; 132, attribute; 133, argument_list; 134, identifier:dist; 135, attribute; 136, identifier:basis; 137, keyword_argument; 138, keyword_argument; 139, keyword_argument; 140, keyword_argument; 141, keyword_argument; 142, identifier:basis; 143, attribute; 144, identifier:gill_king; 145, call; 146, attribute; 147, argument_list; 148, identifier:diag_mesh; 149, call; 150, identifier:cholmat_inv; 151, call; 152, identifier:numpy; 153, identifier:empty; 154, tuple; 155, integer:1; 156, integer:1; 157, integer:1; 158, attribute; 159, argument_list; 160, integer:1; 161, tuple; 162, identifier:dim; 163, identifier:index; 164, subscript; 165, subscript; 166, subscript; 167, attribute; 168, identifier:Poly; 169, identifier:out; 170, identifier:dim; 171, subscript; 172, identifier:float; 173, identifier:chaospy; 174, identifier:poly; 175, identifier:start; 176, integer:1; 177, identifier:stop; 178, identifier:order; 179, identifier:dim; 180, identifier:dim; 181, identifier:sort; 182, identifier:sort; 183, identifier:cross_truncation; 184, identifier:cross_truncation; 185, identifier:chaospy; 186, identifier:chol; 187, attribute; 188, argument_list; 189, attribute; 190, identifier:inv; 191, attribute; 192, attribute; 193, argument_list; 194, attribute; 195, argument_list; 196, binary_operator:length+1; 197, binary_operator:length+1; 198, identifier:numpy; 199, identifier:sum; 200, binary_operator:cholmat_inv*chaospy.descriptives.E(basis, dist, **kws); 201, unary_operator; 202, integer:0; 203, attribute; 204, integer:0; 205, identifier:out; 206, identifier:index; 207, identifier:coefs; 208, binary_operator:idx+1; 209, identifier:chaospy; 210, identifier:poly; 211, attribute; 212, slice; 213, attribute; 214, identifier:Cov; 215, identifier:basis; 216, identifier:dist; 217, identifier:numpy; 218, identifier:linalg; 219, identifier:cholmat; 220, identifier:T; 221, identifier:numpy; 222, identifier:repeat; 223, call; 224, call; 225, identifier:diag_mesh; 226, identifier:reshape; 227, attribute; 228, identifier:length; 229, integer:1; 230, identifier:length; 231, integer:1; 232, identifier:cholmat_inv; 233, call; 234, integer:1; 235, subscript; 236, identifier:keys; 237, identifier:idx; 238, integer:1; 239, identifier:coefs; 240, identifier:shape; 241, integer:1; 242, identifier:chaospy; 243, identifier:descriptives; 244, attribute; 245, argument_list; 246, identifier:len; 247, argument_list; 248, identifier:cholmat_inv; 249, identifier:shape; 250, attribute; 251, argument_list; 252, identifier:basis; 253, identifier:idx; 254, identifier:numpy; 255, identifier:diag; 256, identifier:cholmat_inv; 257, identifier:cholmat_inv; 258, attribute; 259, identifier:E; 260, identifier:basis; 261, identifier:dist; 262, dictionary_splat; 263, identifier:chaospy; 264, identifier:descriptives; 265, identifier:kws | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 4, 25; 4, 26; 4, 27; 4, 28; 4, 29; 7, 30; 7, 31; 8, 32; 8, 33; 9, 34; 9, 35; 10, 36; 11, 37; 12, 38; 13, 39; 14, 40; 15, 41; 16, 42; 17, 43; 17, 44; 18, 45; 19, 46; 20, 47; 21, 48; 22, 49; 23, 50; 24, 51; 25, 52; 26, 53; 27, 54; 27, 55; 27, 56; 28, 57; 29, 58; 38, 59; 38, 60; 39, 61; 39, 62; 40, 63; 40, 64; 41, 65; 41, 66; 42, 67; 42, 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; 55, 90; 55, 91; 56, 92; 56, 93; 57, 94; 57, 95; 60, 96; 60, 97; 62, 98; 62, 99; 64, 100; 64, 101; 66, 102; 66, 103; 68, 104; 68, 105; 70, 106; 71, 107; 73, 108; 73, 109; 74, 110; 74, 111; 74, 112; 76, 113; 76, 114; 76, 115; 78, 116; 78, 117; 78, 118; 81, 119; 82, 120; 82, 121; 82, 122; 85, 123; 85, 124; 88, 125; 88, 126; 89, 127; 89, 128; 91, 129; 92, 130; 93, 131; 95, 132; 95, 133; 97, 134; 98, 135; 98, 136; 99, 137; 99, 138; 99, 139; 99, 140; 99, 141; 101, 142; 102, 143; 102, 144; 103, 145; 104, 146; 104, 147; 106, 148; 106, 149; 107, 150; 107, 151; 108, 152; 108, 153; 109, 154; 111, 155; 112, 156; 118, 157; 119, 158; 119, 159; 121, 160; 126, 161; 126, 162; 130, 163; 130, 164; 131, 165; 131, 166; 132, 167; 132, 168; 133, 169; 133, 170; 133, 171; 133, 172; 135, 173; 135, 174; 137, 175; 137, 176; 138, 177; 138, 178; 139, 179; 139, 180; 140, 181; 140, 182; 141, 183; 141, 184; 143, 185; 143, 186; 145, 187; 145, 188; 146, 189; 146, 190; 147, 191; 149, 192; 149, 193; 151, 194; 151, 195; 154, 196; 154, 197; 158, 198; 158, 199; 159, 200; 159, 201; 161, 202; 164, 203; 164, 204; 165, 205; 165, 206; 166, 207; 166, 208; 167, 209; 167, 210; 171, 211; 171, 212; 187, 213; 187, 214; 188, 215; 188, 216; 189, 217; 189, 218; 191, 219; 191, 220; 192, 221; 192, 222; 193, 223; 193, 224; 194, 225; 194, 226; 195, 227; 196, 228; 196, 229; 197, 230; 197, 231; 200, 232; 200, 233; 201, 234; 203, 235; 203, 236; 208, 237; 208, 238; 211, 239; 211, 240; 212, 241; 213, 242; 213, 243; 223, 244; 223, 245; 224, 246; 224, 247; 227, 248; 227, 249; 233, 250; 233, 251; 235, 252; 235, 253; 244, 254; 244, 255; 245, 256; 247, 257; 250, 258; 250, 259; 251, 260; 251, 261; 251, 262; 258, 263; 258, 264; 262, 265 | def orth_chol(order, dist, normed=True, sort="GR", cross_truncation=1., **kws):
"""
Create orthogonal polynomial expansion from Cholesky decomposition.
Args:
order (int):
Order of polynomial expansion
dist (Dist):
Distribution space where polynomials are orthogonal
normed (bool):
If True orthonormal polynomials will be used instead of monic.
sort (str):
Ordering argument passed to poly.basis. If custom basis is used,
argument is ignored.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Examples:
>>> Z = chaospy.Normal()
>>> print(chaospy.around(chaospy.orth_chol(3, Z), 4))
[1.0, q0, 0.7071q0^2-0.7071, 0.4082q0^3-1.2247q0]
"""
dim = len(dist)
basis = chaospy.poly.basis(
start=1, stop=order, dim=dim, sort=sort,
cross_truncation=cross_truncation,
)
length = len(basis)
cholmat = chaospy.chol.gill_king(chaospy.descriptives.Cov(basis, dist))
cholmat_inv = numpy.linalg.inv(cholmat.T).T
if not normed:
diag_mesh = numpy.repeat(numpy.diag(cholmat_inv), len(cholmat_inv))
cholmat_inv /= diag_mesh.reshape(cholmat_inv.shape)
coefs = numpy.empty((length+1, length+1))
coefs[1:, 1:] = cholmat_inv
coefs[0, 0] = 1
coefs[0, 1:] = 0
expected = -numpy.sum(
cholmat_inv*chaospy.descriptives.E(basis, dist, **kws), -1)
coefs[1:, 0] = expected
coefs = coefs.T
out = {}
out[(0,)*dim] = coefs[0]
for idx in range(length):
index = basis[idx].keys[0]
out[index] = coefs[idx+1]
polynomials = chaospy.poly.Poly(out, dim, coefs.shape[1:], float)
return polynomials |
0, module; 1, function_definition; 2, function_name:sort_key; 3, parameters; 4, block; 5, identifier:val; 6, expression_statement; 7, return_statement; 8, comment:"""Sort key for sorting keys in grevlex order."""; 9, call; 10, attribute; 11, argument_list; 12, identifier:numpy; 13, identifier:sum; 14, binary_operator:(max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val; 15, binary_operator:(max(val)+1)**numpy.arange(len(val)-1, -1, -1); 16, identifier:val; 17, parenthesized_expression; 18, call; 19, binary_operator:max(val)+1; 20, attribute; 21, argument_list; 22, call; 23, integer:1; 24, identifier:numpy; 25, identifier:arange; 26, binary_operator:len(val)-1; 27, unary_operator; 28, unary_operator; 29, identifier:max; 30, argument_list; 31, call; 32, integer:1; 33, integer:1; 34, integer:1; 35, identifier:val; 36, identifier:len; 37, argument_list; 38, identifier:val | 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; 14, 15; 14, 16; 15, 17; 15, 18; 17, 19; 18, 20; 18, 21; 19, 22; 19, 23; 20, 24; 20, 25; 21, 26; 21, 27; 21, 28; 22, 29; 22, 30; 26, 31; 26, 32; 27, 33; 28, 34; 30, 35; 31, 36; 31, 37; 37, 38 | def sort_key(val):
"""Sort key for sorting keys in grevlex order."""
return numpy.sum((max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val) |
0, module; 1, function_definition; 2, function_name:orth_gs; 3, parameters; 4, block; 5, identifier:order; 6, identifier:dist; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, dictionary_splat_pattern; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, if_statement; 15, expression_statement; 16, expression_statement; 17, if_statement; 18, return_statement; 19, identifier:normed; 20, False; 21, identifier:sort; 22, string:"GR"; 23, identifier:cross_truncation; 24, float:1.; 25, identifier:kws; 26, comment:"""
Gram-Schmidt process for generating orthogonal polynomials.
Args:
order (int, Poly):
The upper polynomial order. Alternative a custom polynomial basis
can be used.
dist (Dist):
Weighting distribution(s) defining orthogonality.
normed (bool):
If True orthonormal polynomials will be used instead of monic.
sort (str):
Ordering argument passed to poly.basis. If custom basis is used,
argument is ignored.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly):
The orthogonal polynomial expansion.
Examples:
>>> Z = chaospy.J(chaospy.Normal(), chaospy.Normal())
>>> print(chaospy.around(chaospy.orth_gs(2, Z), 4))
[1.0, q1, q0, q1^2-1.0, q0q1, q0^2-1.0]
"""; 27, assignment; 28, assignment; 29, call; 30, block; 31, else_clause; 32, assignment; 33, assignment; 34, identifier:normed; 35, block; 36, else_clause; 37, call; 38, identifier:logger; 39, call; 40, identifier:dim; 41, call; 42, identifier:isinstance; 43, argument_list; 44, if_statement; 45, expression_statement; 46, block; 47, identifier:basis; 48, call; 49, identifier:polynomials; 50, list; 51, for_statement; 52, block; 53, attribute; 54, argument_list; 55, attribute; 56, argument_list; 57, identifier:len; 58, argument_list; 59, identifier:order; 60, identifier:int; 61, comparison_operator:order == 0; 62, block; 63, assignment; 64, expression_statement; 65, identifier:list; 66, argument_list; 67, subscript; 68, identifier:idx; 69, call; 70, comment:# orthogonalize polynomial:; 71, block; 72, expression_statement; 73, for_statement; 74, attribute; 75, identifier:Poly; 76, identifier:polynomials; 77, keyword_argument; 78, keyword_argument; 79, identifier:logging; 80, identifier:getLogger; 81, identifier:__name__; 82, identifier:dist; 83, identifier:order; 84, integer:0; 85, return_statement; 86, identifier:basis; 87, call; 88, assignment; 89, identifier:basis; 90, identifier:basis; 91, integer:0; 92, identifier:range; 93, argument_list; 94, for_statement; 95, comment:# normalize:; 96, expression_statement; 97, if_statement; 98, expression_statement; 99, expression_statement; 100, assignment; 101, identifier:idx; 102, call; 103, comment:# orthogonalize polynomial:; 104, block; 105, identifier:chaospy; 106, identifier:poly; 107, identifier:dim; 108, identifier:dim; 109, identifier:shape; 110, tuple; 111, call; 112, attribute; 113, argument_list; 114, identifier:basis; 115, identifier:order; 116, integer:1; 117, call; 118, identifier:idy; 119, call; 120, block; 121, assignment; 122, comparison_operator:norms <= 0; 123, block; 124, assignment; 125, call; 126, identifier:norms; 127, list; 128, identifier:range; 129, argument_list; 130, for_statement; 131, expression_statement; 132, if_statement; 133, expression_statement; 134, call; 135, attribute; 136, argument_list; 137, attribute; 138, identifier:basis; 139, integer:0; 140, identifier:order; 141, identifier:dim; 142, identifier:sort; 143, keyword_argument; 144, identifier:len; 145, argument_list; 146, identifier:range; 147, argument_list; 148, expression_statement; 149, expression_statement; 150, identifier:norms; 151, call; 152, identifier:norms; 153, integer:0; 154, expression_statement; 155, break_statement; 156, subscript; 157, binary_operator:basis[idx] / numpy.sqrt(norms); 158, attribute; 159, argument_list; 160, float:1.; 161, integer:1; 162, call; 163, identifier:idy; 164, call; 165, block; 166, call; 167, comparison_operator:norms[-1] <= 0; 168, block; 169, call; 170, identifier:len; 171, argument_list; 172, attribute; 173, identifier:Poly; 174, integer:1; 175, keyword_argument; 176, identifier:chaospy; 177, identifier:poly; 178, identifier:cross_truncation; 179, identifier:cross_truncation; 180, identifier:basis; 181, identifier:idx; 182, assignment; 183, assignment; 184, attribute; 185, argument_list; 186, call; 187, identifier:basis; 188, identifier:idx; 189, subscript; 190, call; 191, identifier:polynomials; 192, identifier:append; 193, subscript; 194, identifier:len; 195, argument_list; 196, identifier:range; 197, argument_list; 198, expression_statement; 199, expression_statement; 200, attribute; 201, argument_list; 202, subscript; 203, integer:0; 204, expression_statement; 205, break_statement; 206, attribute; 207, argument_list; 208, identifier:polynomials; 209, identifier:chaospy; 210, identifier:poly; 211, identifier:dim; 212, identifier:dim; 213, identifier:orth; 214, call; 215, subscript; 216, binary_operator:basis[idx] - polynomials[idy]*orth; 217, attribute; 218, identifier:E; 219, binary_operator:polynomials[-1]**2; 220, identifier:dist; 221, dictionary_splat; 222, attribute; 223, argument_list; 224, identifier:basis; 225, identifier:idx; 226, attribute; 227, argument_list; 228, identifier:basis; 229, identifier:idx; 230, identifier:basis; 231, identifier:idx; 232, assignment; 233, assignment; 234, identifier:norms; 235, identifier:append; 236, call; 237, identifier:norms; 238, unary_operator; 239, call; 240, identifier:polynomials; 241, identifier:append; 242, subscript; 243, attribute; 244, argument_list; 245, identifier:basis; 246, identifier:idx; 247, subscript; 248, binary_operator:polynomials[idy]*orth; 249, identifier:chaospy; 250, identifier:descriptives; 251, subscript; 252, integer:2; 253, identifier:kws; 254, identifier:logger; 255, identifier:warning; 256, string:"Warning: Polynomial cutoff at term %d"; 257, identifier:idx; 258, identifier:numpy; 259, identifier:sqrt; 260, identifier:norms; 261, identifier:orth; 262, call; 263, subscript; 264, binary_operator:basis[idx] - polynomials[idy] * orth / norms[idy]; 265, attribute; 266, argument_list; 267, integer:1; 268, attribute; 269, argument_list; 270, identifier:basis; 271, identifier:idx; 272, attribute; 273, identifier:E; 274, binary_operator:basis[idx]*polynomials[idy]; 275, identifier:dist; 276, dictionary_splat; 277, identifier:basis; 278, identifier:idx; 279, subscript; 280, identifier:orth; 281, identifier:polynomials; 282, unary_operator; 283, attribute; 284, argument_list; 285, identifier:basis; 286, identifier:idx; 287, subscript; 288, binary_operator:polynomials[idy] * orth / norms[idy]; 289, attribute; 290, identifier:E; 291, binary_operator:polynomials[-1]**2; 292, identifier:dist; 293, dictionary_splat; 294, identifier:logger; 295, identifier:warning; 296, string:"Warning: Polynomial cutoff at term %d"; 297, identifier:idx; 298, identifier:chaospy; 299, identifier:descriptives; 300, subscript; 301, subscript; 302, identifier:kws; 303, identifier:polynomials; 304, identifier:idy; 305, integer:1; 306, attribute; 307, identifier:E; 308, binary_operator:basis[idx]*polynomials[idy]; 309, identifier:dist; 310, dictionary_splat; 311, identifier:basis; 312, identifier:idx; 313, binary_operator:polynomials[idy] * orth; 314, subscript; 315, identifier:chaospy; 316, identifier:descriptives; 317, subscript; 318, integer:2; 319, identifier:kws; 320, identifier:basis; 321, identifier:idx; 322, identifier:polynomials; 323, identifier:idy; 324, identifier:chaospy; 325, identifier:descriptives; 326, subscript; 327, subscript; 328, identifier:kws; 329, subscript; 330, identifier:orth; 331, identifier:norms; 332, identifier:idy; 333, identifier:polynomials; 334, unary_operator; 335, identifier:basis; 336, identifier:idx; 337, identifier:polynomials; 338, identifier:idy; 339, identifier:polynomials; 340, identifier:idy; 341, integer:1 | 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; 7, 19; 7, 20; 8, 21; 8, 22; 9, 23; 9, 24; 10, 25; 11, 26; 12, 27; 13, 28; 14, 29; 14, 30; 14, 31; 15, 32; 16, 33; 17, 34; 17, 35; 17, 36; 18, 37; 27, 38; 27, 39; 28, 40; 28, 41; 29, 42; 29, 43; 30, 44; 30, 45; 31, 46; 32, 47; 32, 48; 33, 49; 33, 50; 35, 51; 36, 52; 37, 53; 37, 54; 39, 55; 39, 56; 41, 57; 41, 58; 43, 59; 43, 60; 44, 61; 44, 62; 45, 63; 46, 64; 48, 65; 48, 66; 50, 67; 51, 68; 51, 69; 51, 70; 51, 71; 52, 72; 52, 73; 53, 74; 53, 75; 54, 76; 54, 77; 54, 78; 55, 79; 55, 80; 56, 81; 58, 82; 61, 83; 61, 84; 62, 85; 63, 86; 63, 87; 64, 88; 66, 89; 67, 90; 67, 91; 69, 92; 69, 93; 71, 94; 71, 95; 71, 96; 71, 97; 71, 98; 71, 99; 72, 100; 73, 101; 73, 102; 73, 103; 73, 104; 74, 105; 74, 106; 77, 107; 77, 108; 78, 109; 78, 110; 85, 111; 87, 112; 87, 113; 88, 114; 88, 115; 93, 116; 93, 117; 94, 118; 94, 119; 94, 120; 96, 121; 97, 122; 97, 123; 98, 124; 99, 125; 100, 126; 100, 127; 102, 128; 102, 129; 104, 130; 104, 131; 104, 132; 104, 133; 110, 134; 111, 135; 111, 136; 112, 137; 112, 138; 113, 139; 113, 140; 113, 141; 113, 142; 113, 143; 117, 144; 117, 145; 119, 146; 119, 147; 120, 148; 120, 149; 121, 150; 121, 151; 122, 152; 122, 153; 123, 154; 123, 155; 124, 156; 124, 157; 125, 158; 125, 159; 127, 160; 129, 161; 129, 162; 130, 163; 130, 164; 130, 165; 131, 166; 132, 167; 132, 168; 133, 169; 134, 170; 134, 171; 135, 172; 135, 173; 136, 174; 136, 175; 137, 176; 137, 177; 143, 178; 143, 179; 145, 180; 147, 181; 148, 182; 149, 183; 151, 184; 151, 185; 154, 186; 156, 187; 156, 188; 157, 189; 157, 190; 158, 191; 158, 192; 159, 193; 162, 194; 162, 195; 164, 196; 164, 197; 165, 198; 165, 199; 166, 200; 166, 201; 167, 202; 167, 203; 168, 204; 168, 205; 169, 206; 169, 207; 171, 208; 172, 209; 172, 210; 175, 211; 175, 212; 182, 213; 182, 214; 183, 215; 183, 216; 184, 217; 184, 218; 185, 219; 185, 220; 185, 221; 186, 222; 186, 223; 189, 224; 189, 225; 190, 226; 190, 227; 193, 228; 193, 229; 195, 230; 197, 231; 198, 232; 199, 233; 200, 234; 200, 235; 201, 236; 202, 237; 202, 238; 204, 239; 206, 240; 206, 241; 207, 242; 214, 243; 214, 244; 215, 245; 215, 246; 216, 247; 216, 248; 217, 249; 217, 250; 219, 251; 219, 252; 221, 253; 222, 254; 222, 255; 223, 256; 223, 257; 226, 258; 226, 259; 227, 260; 232, 261; 232, 262; 233, 263; 233, 264; 236, 265; 236, 266; 238, 267; 239, 268; 239, 269; 242, 270; 242, 271; 243, 272; 243, 273; 244, 274; 244, 275; 244, 276; 247, 277; 247, 278; 248, 279; 248, 280; 251, 281; 251, 282; 262, 283; 262, 284; 263, 285; 263, 286; 264, 287; 264, 288; 265, 289; 265, 290; 266, 291; 266, 292; 266, 293; 268, 294; 268, 295; 269, 296; 269, 297; 272, 298; 272, 299; 274, 300; 274, 301; 276, 302; 279, 303; 279, 304; 282, 305; 283, 306; 283, 307; 284, 308; 284, 309; 284, 310; 287, 311; 287, 312; 288, 313; 288, 314; 289, 315; 289, 316; 291, 317; 291, 318; 293, 319; 300, 320; 300, 321; 301, 322; 301, 323; 306, 324; 306, 325; 308, 326; 308, 327; 310, 328; 313, 329; 313, 330; 314, 331; 314, 332; 317, 333; 317, 334; 326, 335; 326, 336; 327, 337; 327, 338; 329, 339; 329, 340; 334, 341 | def orth_gs(order, dist, normed=False, sort="GR", cross_truncation=1., **kws):
"""
Gram-Schmidt process for generating orthogonal polynomials.
Args:
order (int, Poly):
The upper polynomial order. Alternative a custom polynomial basis
can be used.
dist (Dist):
Weighting distribution(s) defining orthogonality.
normed (bool):
If True orthonormal polynomials will be used instead of monic.
sort (str):
Ordering argument passed to poly.basis. If custom basis is used,
argument is ignored.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly):
The orthogonal polynomial expansion.
Examples:
>>> Z = chaospy.J(chaospy.Normal(), chaospy.Normal())
>>> print(chaospy.around(chaospy.orth_gs(2, Z), 4))
[1.0, q1, q0, q1^2-1.0, q0q1, q0^2-1.0]
"""
logger = logging.getLogger(__name__)
dim = len(dist)
if isinstance(order, int):
if order == 0:
return chaospy.poly.Poly(1, dim=dim)
basis = chaospy.poly.basis(
0, order, dim, sort, cross_truncation=cross_truncation)
else:
basis = order
basis = list(basis)
polynomials = [basis[0]]
if normed:
for idx in range(1, len(basis)):
# orthogonalize polynomial:
for idy in range(idx):
orth = chaospy.descriptives.E(
basis[idx]*polynomials[idy], dist, **kws)
basis[idx] = basis[idx] - polynomials[idy]*orth
# normalize:
norms = chaospy.descriptives.E(polynomials[-1]**2, dist, **kws)
if norms <= 0:
logger.warning("Warning: Polynomial cutoff at term %d", idx)
break
basis[idx] = basis[idx] / numpy.sqrt(norms)
polynomials.append(basis[idx])
else:
norms = [1.]
for idx in range(1, len(basis)):
# orthogonalize polynomial:
for idy in range(idx):
orth = chaospy.descriptives.E(
basis[idx]*polynomials[idy], dist, **kws)
basis[idx] = basis[idx] - polynomials[idy] * orth / norms[idy]
norms.append(
chaospy.descriptives.E(polynomials[-1]**2, dist, **kws))
if norms[-1] <= 0:
logger.warning("Warning: Polynomial cutoff at term %d", idx)
break
polynomials.append(basis[idx])
return chaospy.poly.Poly(polynomials, dim=dim, shape=(len(polynomials),)) |
0, module; 1, function_definition; 2, function_name:basis; 3, parameters; 4, block; 5, identifier:start; 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, if_statement; 17, if_statement; 18, expression_statement; 19, expression_statement; 20, expression_statement; 21, expression_statement; 22, for_statement; 23, expression_statement; 24, expression_statement; 25, expression_statement; 26, for_statement; 27, return_statement; 28, identifier:stop; 29, None; 30, identifier:dim; 31, integer:1; 32, identifier:sort; 33, string:"G"; 34, identifier:cross_truncation; 35, float:1.; 36, comment:"""
Create an N-dimensional unit polynomial basis.
Args:
start (int, numpy.ndarray):
the minimum polynomial to include. If int is provided, set as
lowest total order. If array of int, set as lower order along each
axis.
stop (int, numpy.ndarray):
the maximum shape included. If omitted:
``stop <- start; start <- 0`` If int is provided, set as largest
total order. If array of int, set as largest order along each axis.
dim (int):
dim of the basis. Ignored if array is provided in either start or
stop.
sort (str):
The polynomial ordering where the letters ``G``, ``I`` and ``R``
can be used to set grade, inverse and reverse to the ordering. For
``basis(start=0, stop=2, dim=2, order=order)`` we get:
====== ==================
order output
====== ==================
"" [1 y y^2 x xy x^2]
"G" [1 y x y^2 xy x^2]
"I" [x^2 xy x y^2 y 1]
"R" [1 x x^2 y xy y^2]
"GIR" [y^2 xy x^2 y x 1]
====== ==================
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly) : Polynomial array.
Examples:
>>> print(chaospy.basis(4, 4, 2))
[q0^4, q0^3q1, q0^2q1^2, q0q1^3, q1^4]
>>> print(chaospy.basis([1, 1], [2, 2]))
[q0q1, q0^2q1, q0q1^2, q0^2q1^2]
"""; 37, comparison_operator:stop is None; 38, block; 39, assignment; 40, assignment; 41, assignment; 42, assignment; 43, comparison_operator:start.size == 1; 44, block; 45, else_clause; 46, comparison_operator:stop.size == 1; 47, block; 48, else_clause; 49, assignment; 50, assignment; 51, assignment; 52, assignment; 53, identifier:idx; 54, identifier:pool; 55, block; 56, assignment; 57, assignment; 58, assignment; 59, identifier:I; 60, identifier:pool; 61, block; 62, call; 63, identifier:stop; 64, None; 65, expression_statement; 66, identifier:start; 67, call; 68, identifier:stop; 69, call; 70, identifier:dim; 71, call; 72, identifier:indices; 73, call; 74, attribute; 75, integer:1; 76, expression_statement; 77, block; 78, attribute; 79, integer:1; 80, expression_statement; 81, block; 82, identifier:pool; 83, call; 84, identifier:arg; 85, call; 86, subscript; 87, integer:1; 88, identifier:poly; 89, dictionary; 90, expression_statement; 91, expression_statement; 92, expression_statement; 93, identifier:x; 94, call; 95, subscript; 96, integer:1; 97, identifier:A; 98, dictionary; 99, expression_statement; 100, expression_statement; 101, expression_statement; 102, identifier:Poly; 103, argument_list; 104, assignment; 105, attribute; 106, argument_list; 107, attribute; 108, argument_list; 109, identifier:max; 110, argument_list; 111, attribute; 112, argument_list; 113, identifier:start; 114, identifier:size; 115, assignment; 116, expression_statement; 117, expression_statement; 118, identifier:stop; 119, identifier:size; 120, assignment; 121, expression_statement; 122, expression_statement; 123, identifier:list; 124, argument_list; 125, attribute; 126, argument_list; 127, identifier:arg; 128, integer:0; 129, assignment; 130, assignment; 131, assignment; 132, attribute; 133, argument_list; 134, identifier:x; 135, integer:0; 136, assignment; 137, assignment; 138, assignment; 139, identifier:A; 140, identifier:dim; 141, pattern_list; 142, expression_list; 143, identifier:numpy; 144, identifier:array; 145, identifier:start; 146, keyword_argument; 147, identifier:numpy; 148, identifier:array; 149, identifier:stop; 150, keyword_argument; 151, attribute; 152, attribute; 153, identifier:dim; 154, identifier:numpy; 155, identifier:array; 156, call; 157, identifier:bellow; 158, comparison_operator:numpy.sum(indices, -1) >= start; 159, assignment; 160, assignment; 161, identifier:above; 162, comparison_operator:numpy.sum(indices, -1) <= stop.item(); 163, assignment; 164, assignment; 165, subscript; 166, identifier:numpy; 167, identifier:zeros; 168, call; 169, keyword_argument; 170, identifier:idx; 171, call; 172, subscript; 173, identifier:arg; 174, identifier:arg; 175, call; 176, identifier:numpy; 177, identifier:zeros; 178, call; 179, keyword_argument; 180, identifier:I; 181, call; 182, subscript; 183, identifier:x; 184, identifier:x; 185, call; 186, identifier:start; 187, identifier:stop; 188, call; 189, identifier:start; 190, identifier:dtype; 191, identifier:int; 192, identifier:dtype; 193, identifier:int; 194, identifier:start; 195, identifier:size; 196, identifier:stop; 197, identifier:size; 198, attribute; 199, argument_list; 200, call; 201, identifier:start; 202, identifier:start; 203, binary_operator:numpy.ones(dim, dtype=int)*start; 204, identifier:bellow; 205, call; 206, call; 207, call; 208, identifier:stop; 209, binary_operator:numpy.ones(dim, dtype=int)*stop; 210, identifier:above; 211, call; 212, identifier:indices; 213, binary_operator:above*bellow; 214, identifier:len; 215, argument_list; 216, identifier:dtype; 217, identifier:int; 218, identifier:tuple; 219, argument_list; 220, identifier:poly; 221, identifier:idx; 222, attribute; 223, argument_list; 224, identifier:len; 225, argument_list; 226, identifier:dtype; 227, identifier:int; 228, identifier:tuple; 229, argument_list; 230, identifier:A; 231, identifier:I; 232, attribute; 233, argument_list; 234, attribute; 235, argument_list; 236, attribute; 237, identifier:bindex; 238, call; 239, binary_operator:2*numpy.max(stop); 240, identifier:dim; 241, identifier:sort; 242, identifier:cross_truncation; 243, attribute; 244, argument_list; 245, call; 246, identifier:start; 247, attribute; 248, argument_list; 249, attribute; 250, argument_list; 251, attribute; 252, argument_list; 253, call; 254, identifier:stop; 255, attribute; 256, argument_list; 257, identifier:above; 258, identifier:bellow; 259, identifier:pool; 260, identifier:idx; 261, identifier:numpy; 262, identifier:roll; 263, identifier:arg; 264, integer:1; 265, identifier:pool; 266, identifier:I; 267, identifier:numpy; 268, identifier:roll; 269, identifier:x; 270, integer:1; 271, identifier:numpy; 272, identifier:array; 273, integer:0; 274, identifier:chaospy; 275, identifier:bertran; 276, attribute; 277, argument_list; 278, integer:2; 279, call; 280, identifier:numpy; 281, identifier:sum; 282, identifier:indices; 283, unary_operator; 284, attribute; 285, argument_list; 286, identifier:numpy; 287, identifier:all; 288, comparison_operator:indices-start >= 0; 289, unary_operator; 290, identifier:numpy; 291, identifier:sum; 292, identifier:indices; 293, unary_operator; 294, identifier:stop; 295, identifier:item; 296, attribute; 297, argument_list; 298, identifier:numpy; 299, identifier:all; 300, comparison_operator:stop-indices >= 0; 301, unary_operator; 302, identifier:numpy; 303, identifier:min; 304, identifier:start; 305, attribute; 306, argument_list; 307, integer:1; 308, identifier:numpy; 309, identifier:ones; 310, identifier:dim; 311, keyword_argument; 312, binary_operator:indices-start; 313, integer:0; 314, integer:1; 315, integer:1; 316, identifier:numpy; 317, identifier:ones; 318, identifier:dim; 319, keyword_argument; 320, binary_operator:stop-indices; 321, integer:0; 322, integer:1; 323, identifier:numpy; 324, identifier:max; 325, identifier:stop; 326, identifier:dtype; 327, identifier:int; 328, identifier:indices; 329, identifier:start; 330, identifier:dtype; 331, identifier:int; 332, identifier:stop; 333, identifier:indices | 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; 6, 28; 6, 29; 7, 30; 7, 31; 8, 32; 8, 33; 9, 34; 9, 35; 10, 36; 11, 37; 11, 38; 12, 39; 13, 40; 14, 41; 15, 42; 16, 43; 16, 44; 16, 45; 17, 46; 17, 47; 17, 48; 18, 49; 19, 50; 20, 51; 21, 52; 22, 53; 22, 54; 22, 55; 23, 56; 24, 57; 25, 58; 26, 59; 26, 60; 26, 61; 27, 62; 37, 63; 37, 64; 38, 65; 39, 66; 39, 67; 40, 68; 40, 69; 41, 70; 41, 71; 42, 72; 42, 73; 43, 74; 43, 75; 44, 76; 45, 77; 46, 78; 46, 79; 47, 80; 48, 81; 49, 82; 49, 83; 50, 84; 50, 85; 51, 86; 51, 87; 52, 88; 52, 89; 55, 90; 55, 91; 55, 92; 56, 93; 56, 94; 57, 95; 57, 96; 58, 97; 58, 98; 61, 99; 61, 100; 61, 101; 62, 102; 62, 103; 65, 104; 67, 105; 67, 106; 69, 107; 69, 108; 71, 109; 71, 110; 73, 111; 73, 112; 74, 113; 74, 114; 76, 115; 77, 116; 77, 117; 78, 118; 78, 119; 80, 120; 81, 121; 81, 122; 83, 123; 83, 124; 85, 125; 85, 126; 86, 127; 86, 128; 90, 129; 91, 130; 92, 131; 94, 132; 94, 133; 95, 134; 95, 135; 99, 136; 100, 137; 101, 138; 103, 139; 103, 140; 104, 141; 104, 142; 105, 143; 105, 144; 106, 145; 106, 146; 107, 147; 107, 148; 108, 149; 108, 150; 110, 151; 110, 152; 110, 153; 111, 154; 111, 155; 112, 156; 115, 157; 115, 158; 116, 159; 117, 160; 120, 161; 120, 162; 121, 163; 122, 164; 124, 165; 125, 166; 125, 167; 126, 168; 126, 169; 129, 170; 129, 171; 130, 172; 130, 173; 131, 174; 131, 175; 132, 176; 132, 177; 133, 178; 133, 179; 136, 180; 136, 181; 137, 182; 137, 183; 138, 184; 138, 185; 141, 186; 141, 187; 142, 188; 142, 189; 146, 190; 146, 191; 150, 192; 150, 193; 151, 194; 151, 195; 152, 196; 152, 197; 156, 198; 156, 199; 158, 200; 158, 201; 159, 202; 159, 203; 160, 204; 160, 205; 162, 206; 162, 207; 163, 208; 163, 209; 164, 210; 164, 211; 165, 212; 165, 213; 168, 214; 168, 215; 169, 216; 169, 217; 171, 218; 171, 219; 172, 220; 172, 221; 175, 222; 175, 223; 178, 224; 178, 225; 179, 226; 179, 227; 181, 228; 181, 229; 182, 230; 182, 231; 185, 232; 185, 233; 188, 234; 188, 235; 198, 236; 198, 237; 199, 238; 199, 239; 199, 240; 199, 241; 199, 242; 200, 243; 200, 244; 203, 245; 203, 246; 205, 247; 205, 248; 206, 249; 206, 250; 207, 251; 207, 252; 209, 253; 209, 254; 211, 255; 211, 256; 213, 257; 213, 258; 215, 259; 219, 260; 222, 261; 222, 262; 223, 263; 223, 264; 225, 265; 229, 266; 232, 267; 232, 268; 233, 269; 233, 270; 234, 271; 234, 272; 235, 273; 236, 274; 236, 275; 238, 276; 238, 277; 239, 278; 239, 279; 243, 280; 243, 281; 244, 282; 244, 283; 245, 284; 245, 285; 247, 286; 247, 287; 248, 288; 248, 289; 249, 290; 249, 291; 250, 292; 250, 293; 251, 294; 251, 295; 253, 296; 253, 297; 255, 298; 255, 299; 256, 300; 256, 301; 276, 302; 276, 303; 277, 304; 279, 305; 279, 306; 283, 307; 284, 308; 284, 309; 285, 310; 285, 311; 288, 312; 288, 313; 289, 314; 293, 315; 296, 316; 296, 317; 297, 318; 297, 319; 300, 320; 300, 321; 301, 322; 305, 323; 305, 324; 306, 325; 311, 326; 311, 327; 312, 328; 312, 329; 319, 330; 319, 331; 320, 332; 320, 333 | def basis(start, stop=None, dim=1, sort="G", cross_truncation=1.):
"""
Create an N-dimensional unit polynomial basis.
Args:
start (int, numpy.ndarray):
the minimum polynomial to include. If int is provided, set as
lowest total order. If array of int, set as lower order along each
axis.
stop (int, numpy.ndarray):
the maximum shape included. If omitted:
``stop <- start; start <- 0`` If int is provided, set as largest
total order. If array of int, set as largest order along each axis.
dim (int):
dim of the basis. Ignored if array is provided in either start or
stop.
sort (str):
The polynomial ordering where the letters ``G``, ``I`` and ``R``
can be used to set grade, inverse and reverse to the ordering. For
``basis(start=0, stop=2, dim=2, order=order)`` we get:
====== ==================
order output
====== ==================
"" [1 y y^2 x xy x^2]
"G" [1 y x y^2 xy x^2]
"I" [x^2 xy x y^2 y 1]
"R" [1 x x^2 y xy y^2]
"GIR" [y^2 xy x^2 y x 1]
====== ==================
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly) : Polynomial array.
Examples:
>>> print(chaospy.basis(4, 4, 2))
[q0^4, q0^3q1, q0^2q1^2, q0q1^3, q1^4]
>>> print(chaospy.basis([1, 1], [2, 2]))
[q0q1, q0^2q1, q0q1^2, q0^2q1^2]
"""
if stop is None:
start, stop = numpy.array(0), start
start = numpy.array(start, dtype=int)
stop = numpy.array(stop, dtype=int)
dim = max(start.size, stop.size, dim)
indices = numpy.array(chaospy.bertran.bindex(
numpy.min(start), 2*numpy.max(stop), dim, sort, cross_truncation))
if start.size == 1:
bellow = numpy.sum(indices, -1) >= start
else:
start = numpy.ones(dim, dtype=int)*start
bellow = numpy.all(indices-start >= 0, -1)
if stop.size == 1:
above = numpy.sum(indices, -1) <= stop.item()
else:
stop = numpy.ones(dim, dtype=int)*stop
above = numpy.all(stop-indices >= 0, -1)
pool = list(indices[above*bellow])
arg = numpy.zeros(len(pool), dtype=int)
arg[0] = 1
poly = {}
for idx in pool:
idx = tuple(idx)
poly[idx] = arg
arg = numpy.roll(arg, 1)
x = numpy.zeros(len(pool), dtype=int)
x[0] = 1
A = {}
for I in pool:
I = tuple(I)
A[I] = x
x = numpy.roll(x,1)
return Poly(A, dim) |
0, module; 1, function_definition; 2, function_name:sorted; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, return_statement; 10, identifier:key; 11, None; 12, identifier:reverse; 13, False; 14, comment:"""
Uses python sort and its passed arguments to sort the input.
>>> seq([2, 1, 4, 3]).sorted()
[1, 2, 3, 4]
:param key: sort using key function
:param reverse: return list reversed or not
:return: sorted sequence
"""; 15, call; 16, attribute; 17, argument_list; 18, identifier:self; 19, identifier:_transform; 20, call; 21, attribute; 22, argument_list; 23, identifier:transformations; 24, identifier:sorted_t; 25, keyword_argument; 26, keyword_argument; 27, identifier:key; 28, identifier:key; 29, identifier:reverse; 30, identifier:reverse | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 6, 10; 6, 11; 7, 12; 7, 13; 8, 14; 9, 15; 15, 16; 15, 17; 16, 18; 16, 19; 17, 20; 20, 21; 20, 22; 21, 23; 21, 24; 22, 25; 22, 26; 25, 27; 25, 28; 26, 29; 26, 30 | def sorted(self, key=None, reverse=False):
"""
Uses python sort and its passed arguments to sort the input.
>>> seq([2, 1, 4, 3]).sorted()
[1, 2, 3, 4]
:param key: sort using key function
:param reverse: return list reversed or not
:return: sorted sequence
"""
return self._transform(transformations.sorted_t(key=key, reverse=reverse)) |
0, module; 1, function_definition; 2, function_name:GetCredentials; 3, parameters; 4, block; 5, identifier:package_name; 6, identifier:scopes; 7, identifier:client_id; 8, identifier:client_secret; 9, identifier:user_agent; 10, default_parameter; 11, default_parameter; 12, comment:# pylint: disable=unused-argument; 13, default_parameter; 14, comment:# pylint: disable=unused-argument; 15, default_parameter; 16, dictionary_splat_pattern; 17, expression_statement; 18, expression_statement; 19, expression_statement; 20, for_statement; 21, expression_statement; 22, expression_statement; 23, if_statement; 24, raise_statement; 25, identifier:credentials_filename; 26, None; 27, identifier:api_key; 28, None; 29, identifier:client; 30, None; 31, identifier:oauth2client_args; 32, None; 33, identifier:kwds; 34, comment:"""Attempt to get credentials, using an oauth dance as the last resort."""; 35, assignment; 36, assignment; 37, identifier:method; 38, identifier:_CREDENTIALS_METHODS; 39, block; 40, assignment; 41, assignment; 42, comparison_operator:credentials is not None; 43, block; 44, call; 45, identifier:scopes; 46, call; 47, identifier:client_info; 48, dictionary; 49, expression_statement; 50, if_statement; 51, identifier:credentials_filename; 52, boolean_operator; 53, identifier:credentials; 54, call; 55, identifier:credentials; 56, None; 57, return_statement; 58, attribute; 59, argument_list; 60, attribute; 61, argument_list; 62, pair; 63, pair; 64, pair; 65, pair; 66, assignment; 67, comparison_operator:credentials is not None; 68, block; 69, identifier:credentials_filename; 70, call; 71, identifier:CredentialsFromFile; 72, argument_list; 73, identifier:credentials; 74, identifier:exceptions; 75, identifier:CredentialsError; 76, string; 77, identifier:util; 78, identifier:NormalizeScopes; 79, identifier:scopes; 80, string; 81, identifier:client_id; 82, string; 83, identifier:client_secret; 84, string; 85, call; 86, string; 87, boolean_operator; 88, identifier:credentials; 89, call; 90, identifier:credentials; 91, None; 92, return_statement; 93, attribute; 94, argument_list; 95, identifier:credentials_filename; 96, identifier:client_info; 97, keyword_argument; 98, string_content:Could not create valid credentials; 99, string_content:client_id; 100, string_content:client_secret; 101, string_content:scope; 102, attribute; 103, argument_list; 104, string_content:user_agent; 105, identifier:user_agent; 106, binary_operator:'%s-generated/0.1' % package_name; 107, identifier:method; 108, argument_list; 109, identifier:credentials; 110, attribute; 111, identifier:expanduser; 112, string; 113, identifier:oauth2client_args; 114, identifier:oauth2client_args; 115, string; 116, identifier:join; 117, call; 118, string; 119, identifier:package_name; 120, identifier:client_info; 121, dictionary_splat; 122, identifier:os; 123, identifier:path; 124, string_content:~/.apitools.token; 125, string_content:; 126, identifier:sorted; 127, argument_list; 128, string_content:%s-generated/0.1; 129, identifier:kwds; 130, identifier:scopes | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 3, 14; 3, 15; 3, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 4, 24; 10, 25; 10, 26; 11, 27; 11, 28; 13, 29; 13, 30; 15, 31; 15, 32; 16, 33; 17, 34; 18, 35; 19, 36; 20, 37; 20, 38; 20, 39; 21, 40; 22, 41; 23, 42; 23, 43; 24, 44; 35, 45; 35, 46; 36, 47; 36, 48; 39, 49; 39, 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; 48, 64; 48, 65; 49, 66; 50, 67; 50, 68; 52, 69; 52, 70; 54, 71; 54, 72; 57, 73; 58, 74; 58, 75; 59, 76; 60, 77; 60, 78; 61, 79; 62, 80; 62, 81; 63, 82; 63, 83; 64, 84; 64, 85; 65, 86; 65, 87; 66, 88; 66, 89; 67, 90; 67, 91; 68, 92; 70, 93; 70, 94; 72, 95; 72, 96; 72, 97; 76, 98; 80, 99; 82, 100; 84, 101; 85, 102; 85, 103; 86, 104; 87, 105; 87, 106; 89, 107; 89, 108; 92, 109; 93, 110; 93, 111; 94, 112; 97, 113; 97, 114; 102, 115; 102, 116; 103, 117; 106, 118; 106, 119; 108, 120; 108, 121; 110, 122; 110, 123; 112, 124; 115, 125; 117, 126; 117, 127; 118, 128; 121, 129; 127, 130 | def GetCredentials(package_name, scopes, client_id, client_secret, user_agent,
credentials_filename=None,
api_key=None, # pylint: disable=unused-argument
client=None, # pylint: disable=unused-argument
oauth2client_args=None,
**kwds):
"""Attempt to get credentials, using an oauth dance as the last resort."""
scopes = util.NormalizeScopes(scopes)
client_info = {
'client_id': client_id,
'client_secret': client_secret,
'scope': ' '.join(sorted(scopes)),
'user_agent': user_agent or '%s-generated/0.1' % package_name,
}
for method in _CREDENTIALS_METHODS:
credentials = method(client_info, **kwds)
if credentials is not None:
return credentials
credentials_filename = credentials_filename or os.path.expanduser(
'~/.apitools.token')
credentials = CredentialsFromFile(credentials_filename, client_info,
oauth2client_args=oauth2client_args)
if credentials is not None:
return credentials
raise exceptions.CredentialsError('Could not create valid credentials') |
0, module; 1, function_definition; 2, function_name:get_sorted_graph; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, expression_statement; 12, if_statement; 13, with_statement; 14, if_statement; 15, return_statement; 16, identifier:start; 17, integer:0; 18, identifier:stop; 19, integer:100; 20, identifier:slices; 21, integer:100; 22, identifier:include_inf; 23, False; 24, identifier:exact; 25, False; 26, comment:""" Returns a graph of the distribution of jobs in a sorted set """; 27, not_operator; 28, block; 29, with_clause; 30, block; 31, identifier:include_inf; 32, block; 33, identifier:data; 34, attribute; 35, raise_statement; 36, with_item; 37, expression_statement; 38, for_statement; 39, if_statement; 40, expression_statement; 41, return_statement; 42, identifier:self; 43, identifier:is_sorted; 44, call; 45, as_pattern; 46, assignment; 47, identifier:i; 48, call; 49, block; 50, identifier:include_inf; 51, block; 52, assignment; 53, binary_operator:data[-1:] + data[:-1]; 54, identifier:Exception; 55, argument_list; 56, call; 57, as_pattern_target; 58, identifier:interval; 59, call; 60, identifier:range; 61, argument_list; 62, expression_statement; 63, expression_statement; 64, expression_statement; 65, identifier:data; 66, call; 67, subscript; 68, subscript; 69, string:"Not a sorted queue"; 70, attribute; 71, argument_list; 72, identifier:pipe; 73, identifier:old_div; 74, argument_list; 75, integer:0; 76, identifier:slices; 77, call; 78, call; 79, call; 80, attribute; 81, argument_list; 82, identifier:data; 83, slice; 84, identifier:data; 85, slice; 86, attribute; 87, identifier:pipeline; 88, keyword_argument; 89, call; 90, identifier:slices; 91, attribute; 92, argument_list; 93, attribute; 94, argument_list; 95, attribute; 96, argument_list; 97, identifier:pipe; 98, identifier:execute; 99, unary_operator; 100, unary_operator; 101, attribute; 102, identifier:redis; 103, identifier:transaction; 104, identifier:exact; 105, identifier:float; 106, argument_list; 107, identifier:pipe; 108, identifier:zcount; 109, attribute; 110, parenthesized_expression; 111, binary_operator:"(%s" % (start + (i + 1) * interval); 112, identifier:pipe; 113, identifier:zcount; 114, attribute; 115, identifier:stop; 116, string:"+inf"; 117, identifier:pipe; 118, identifier:zcount; 119, attribute; 120, string:"-inf"; 121, binary_operator:"(%s" % start; 122, integer:1; 123, integer:1; 124, identifier:context; 125, identifier:connections; 126, binary_operator:stop - start; 127, identifier:self; 128, identifier:redis_key; 129, binary_operator:start + i * interval; 130, string:"(%s"; 131, parenthesized_expression; 132, identifier:self; 133, identifier:redis_key; 134, identifier:self; 135, identifier:redis_key; 136, string:"(%s"; 137, identifier:start; 138, identifier:stop; 139, identifier:start; 140, identifier:start; 141, binary_operator:i * interval; 142, binary_operator:start + (i + 1) * interval; 143, identifier:i; 144, identifier:interval; 145, identifier:start; 146, binary_operator:(i + 1) * interval; 147, parenthesized_expression; 148, identifier:interval; 149, binary_operator:i + 1; 150, identifier:i; 151, integer:1 | 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; 10, 25; 11, 26; 12, 27; 12, 28; 13, 29; 13, 30; 14, 31; 14, 32; 15, 33; 27, 34; 28, 35; 29, 36; 30, 37; 30, 38; 30, 39; 30, 40; 32, 41; 34, 42; 34, 43; 35, 44; 36, 45; 37, 46; 38, 47; 38, 48; 38, 49; 39, 50; 39, 51; 40, 52; 41, 53; 44, 54; 44, 55; 45, 56; 45, 57; 46, 58; 46, 59; 48, 60; 48, 61; 49, 62; 51, 63; 51, 64; 52, 65; 52, 66; 53, 67; 53, 68; 55, 69; 56, 70; 56, 71; 57, 72; 59, 73; 59, 74; 61, 75; 61, 76; 62, 77; 63, 78; 64, 79; 66, 80; 66, 81; 67, 82; 67, 83; 68, 84; 68, 85; 70, 86; 70, 87; 71, 88; 74, 89; 74, 90; 77, 91; 77, 92; 78, 93; 78, 94; 79, 95; 79, 96; 80, 97; 80, 98; 83, 99; 85, 100; 86, 101; 86, 102; 88, 103; 88, 104; 89, 105; 89, 106; 91, 107; 91, 108; 92, 109; 92, 110; 92, 111; 93, 112; 93, 113; 94, 114; 94, 115; 94, 116; 95, 117; 95, 118; 96, 119; 96, 120; 96, 121; 99, 122; 100, 123; 101, 124; 101, 125; 106, 126; 109, 127; 109, 128; 110, 129; 111, 130; 111, 131; 114, 132; 114, 133; 119, 134; 119, 135; 121, 136; 121, 137; 126, 138; 126, 139; 129, 140; 129, 141; 131, 142; 141, 143; 141, 144; 142, 145; 142, 146; 146, 147; 146, 148; 147, 149; 149, 150; 149, 151 | def get_sorted_graph(
self,
start=0,
stop=100,
slices=100,
include_inf=False,
exact=False):
""" Returns a graph of the distribution of jobs in a sorted set """
if not self.is_sorted:
raise Exception("Not a sorted queue")
with context.connections.redis.pipeline(transaction=exact) as pipe:
interval = old_div(float(stop - start), slices)
for i in range(0, slices):
pipe.zcount(self.redis_key,
(start + i * interval),
"(%s" % (start + (i + 1) * interval))
if include_inf:
pipe.zcount(self.redis_key, stop, "+inf")
pipe.zcount(self.redis_key, "-inf", "(%s" % start)
data = pipe.execute()
if include_inf:
return data[-1:] + data[:-1]
return data |
0, module; 1, function_definition; 2, function_name:get_threads; 3, parameters; 4, block; 5, identifier:self; 6, identifier:querystring; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, assert_statement; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, return_statement; 15, identifier:sort; 16, string; 17, identifier:exclude_tags; 18, None; 19, comment:"""
asynchronously look up thread ids matching `querystring`.
:param querystring: The query string to use for the lookup
:type querystring: str.
:param sort: Sort order. one of ['oldest_first', 'newest_first',
'message_id', 'unsorted']
:type query: str
:param exclude_tags: Tags to exclude by default unless included in the
search
:type exclude_tags: list of str
:returns: a pipe together with the process that asynchronously
writes to it.
:rtype: (:class:`multiprocessing.Pipe`,
:class:`multiprocessing.Process`)
"""; 20, comparison_operator:sort in self._sort_orders; 21, assignment; 22, call; 23, identifier:exclude_tags; 24, block; 25, call; 26, string_content:newest_first; 27, identifier:sort; 28, attribute; 29, identifier:q; 30, call; 31, attribute; 32, argument_list; 33, for_statement; 34, attribute; 35, argument_list; 36, identifier:self; 37, identifier:_sort_orders; 38, attribute; 39, argument_list; 40, identifier:q; 41, identifier:set_sort; 42, subscript; 43, identifier:tag; 44, identifier:exclude_tags; 45, block; 46, identifier:self; 47, identifier:async_; 48, attribute; 49, parenthesized_expression; 50, identifier:self; 51, identifier:query; 52, identifier:querystring; 53, attribute; 54, identifier:sort; 55, expression_statement; 56, identifier:q; 57, identifier:search_threads; 58, lambda; 59, identifier:self; 60, identifier:_sort_orders; 61, call; 62, lambda_parameters; 63, call; 64, attribute; 65, argument_list; 66, identifier:a; 67, attribute; 68, argument_list; 69, identifier:q; 70, identifier:exclude_tag; 71, identifier:tag; 72, identifier:a; 73, identifier:get_thread_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; 7, 15; 7, 16; 8, 17; 8, 18; 9, 19; 10, 20; 11, 21; 12, 22; 13, 23; 13, 24; 14, 25; 16, 26; 20, 27; 20, 28; 21, 29; 21, 30; 22, 31; 22, 32; 24, 33; 25, 34; 25, 35; 28, 36; 28, 37; 30, 38; 30, 39; 31, 40; 31, 41; 32, 42; 33, 43; 33, 44; 33, 45; 34, 46; 34, 47; 35, 48; 35, 49; 38, 50; 38, 51; 39, 52; 42, 53; 42, 54; 45, 55; 48, 56; 48, 57; 49, 58; 53, 59; 53, 60; 55, 61; 58, 62; 58, 63; 61, 64; 61, 65; 62, 66; 63, 67; 63, 68; 64, 69; 64, 70; 65, 71; 67, 72; 67, 73 | def get_threads(self, querystring, sort='newest_first', exclude_tags=None):
"""
asynchronously look up thread ids matching `querystring`.
:param querystring: The query string to use for the lookup
:type querystring: str.
:param sort: Sort order. one of ['oldest_first', 'newest_first',
'message_id', 'unsorted']
:type query: str
:param exclude_tags: Tags to exclude by default unless included in the
search
:type exclude_tags: list of str
:returns: a pipe together with the process that asynchronously
writes to it.
:rtype: (:class:`multiprocessing.Pipe`,
:class:`multiprocessing.Process`)
"""
assert sort in self._sort_orders
q = self.query(querystring)
q.set_sort(self._sort_orders[sort])
if exclude_tags:
for tag in exclude_tags:
q.exclude_tag(tag)
return self.async_(q.search_threads, (lambda a: a.get_thread_id())) |
0, module; 1, function_definition; 2, function_name:nd_sort_samples; 3, parameters; 4, block; 5, identifier:samples; 6, expression_statement; 7, comment:# Check the shape of the sample list.; 8, assert_statement; 9, comment:# Build a KD-tree on the samples.; 10, expression_statement; 11, comment:# Compute the distances.; 12, expression_statement; 13, return_statement; 14, comment:"""
Sort an N-dimensional list of samples using a KDTree.
:param samples: ``(nsamples, ndim)``
The list of samples. This must be a two-dimensional array.
:returns i: ``(nsamples,)``
The list of indices into the original array that return the correctly
sorted version.
"""; 15, comparison_operator:len(samples.shape) == 2; 16, assignment; 17, assignment; 18, identifier:i; 19, call; 20, integer:2; 21, identifier:tree; 22, call; 23, pattern_list; 24, call; 25, identifier:len; 26, argument_list; 27, identifier:cKDTree; 28, argument_list; 29, identifier:d; 30, identifier:i; 31, attribute; 32, argument_list; 33, attribute; 34, identifier:samples; 35, identifier:tree; 36, identifier:query; 37, subscript; 38, keyword_argument; 39, identifier:samples; 40, identifier:shape; 41, identifier:samples; 42, integer:0; 43, identifier:k; 44, call; 45, identifier:len; 46, argument_list; 47, identifier:samples | 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; 8, 15; 10, 16; 12, 17; 13, 18; 15, 19; 15, 20; 16, 21; 16, 22; 17, 23; 17, 24; 19, 25; 19, 26; 22, 27; 22, 28; 23, 29; 23, 30; 24, 31; 24, 32; 26, 33; 28, 34; 31, 35; 31, 36; 32, 37; 32, 38; 33, 39; 33, 40; 37, 41; 37, 42; 38, 43; 38, 44; 44, 45; 44, 46; 46, 47 | def nd_sort_samples(samples):
"""
Sort an N-dimensional list of samples using a KDTree.
:param samples: ``(nsamples, ndim)``
The list of samples. This must be a two-dimensional array.
:returns i: ``(nsamples,)``
The list of indices into the original array that return the correctly
sorted version.
"""
# Check the shape of the sample list.
assert len(samples.shape) == 2
# Build a KD-tree on the samples.
tree = cKDTree(samples)
# Compute the distances.
d, i = tree.query(samples[0], k=len(samples))
return i |
0, module; 1, function_definition; 2, function_name:GetVolumeIdentifiers; 3, parameters; 4, block; 5, identifier:self; 6, identifier:volume_system; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""Retrieves the volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
Returns:
list[str]: sorted volume identifiers.
"""; 12, assignment; 13, identifier:volume; 14, attribute; 15, block; 16, call; 17, identifier:volume_identifiers; 18, list; 19, identifier:volume_system; 20, identifier:volumes; 21, expression_statement; 22, if_statement; 23, identifier:sorted; 24, argument_list; 25, assignment; 26, identifier:volume_identifier; 27, block; 28, identifier:volume_identifiers; 29, identifier:volume_identifier; 30, call; 31, expression_statement; 32, identifier:getattr; 33, argument_list; 34, call; 35, identifier:volume; 36, string; 37, None; 38, attribute; 39, argument_list; 40, string_content:identifier; 41, identifier:volume_identifiers; 42, identifier:append; 43, identifier:volume_identifier | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 14, 19; 14, 20; 15, 21; 15, 22; 16, 23; 16, 24; 21, 25; 22, 26; 22, 27; 24, 28; 25, 29; 25, 30; 27, 31; 30, 32; 30, 33; 31, 34; 33, 35; 33, 36; 33, 37; 34, 38; 34, 39; 36, 40; 38, 41; 38, 42; 39, 43 | def GetVolumeIdentifiers(self, volume_system):
"""Retrieves the volume identifiers.
Args:
volume_system (VolumeSystem): volume system.
Returns:
list[str]: sorted volume identifiers.
"""
volume_identifiers = []
for volume in volume_system.volumes:
volume_identifier = getattr(volume, 'identifier', None)
if volume_identifier:
volume_identifiers.append(volume_identifier)
return sorted(volume_identifiers) |
0, module; 1, function_definition; 2, function_name:topological_order_dfs; 3, parameters; 4, block; 5, identifier:graph; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, for_statement; 11, return_statement; 12, comment:"""Topological sorting by depth first search
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of vertices in order
:complexity: `O(|V|+|E|)`
"""; 13, assignment; 14, assignment; 15, assignment; 16, identifier:start; 17, call; 18, block; 19, subscript; 20, identifier:n; 21, call; 22, identifier:order; 23, list; 24, identifier:times_seen; 25, binary_operator:[-1] * n; 26, identifier:range; 27, argument_list; 28, if_statement; 29, identifier:order; 30, slice; 31, identifier:len; 32, argument_list; 33, list; 34, identifier:n; 35, identifier:n; 36, comparison_operator:times_seen[start] == -1; 37, block; 38, unary_operator; 39, identifier:graph; 40, unary_operator; 41, subscript; 42, unary_operator; 43, expression_statement; 44, expression_statement; 45, while_statement; 46, integer:1; 47, integer:1; 48, identifier:times_seen; 49, identifier:start; 50, integer:1; 51, assignment; 52, assignment; 53, identifier:to_visit; 54, block; 55, subscript; 56, integer:0; 57, identifier:to_visit; 58, list; 59, expression_statement; 60, expression_statement; 61, if_statement; 62, identifier:times_seen; 63, identifier:start; 64, identifier:start; 65, assignment; 66, assignment; 67, comparison_operator:times_seen[node] == len(children); 68, block; 69, else_clause; 70, identifier:node; 71, subscript; 72, identifier:children; 73, subscript; 74, subscript; 75, call; 76, expression_statement; 77, expression_statement; 78, block; 79, identifier:to_visit; 80, unary_operator; 81, identifier:graph; 82, identifier:node; 83, identifier:times_seen; 84, identifier:node; 85, identifier:len; 86, argument_list; 87, call; 88, call; 89, expression_statement; 90, expression_statement; 91, if_statement; 92, integer:1; 93, identifier:children; 94, attribute; 95, argument_list; 96, attribute; 97, argument_list; 98, assignment; 99, augmented_assignment; 100, comparison_operator:times_seen[child] == -1; 101, block; 102, identifier:to_visit; 103, identifier:pop; 104, identifier:order; 105, identifier:append; 106, identifier:node; 107, identifier:child; 108, subscript; 109, subscript; 110, integer:1; 111, subscript; 112, unary_operator; 113, expression_statement; 114, expression_statement; 115, identifier:children; 116, subscript; 117, identifier:times_seen; 118, identifier:node; 119, identifier:times_seen; 120, identifier:child; 121, integer:1; 122, assignment; 123, call; 124, identifier:times_seen; 125, identifier:node; 126, subscript; 127, integer:0; 128, attribute; 129, argument_list; 130, identifier:times_seen; 131, identifier:child; 132, identifier:to_visit; 133, identifier:append; 134, identifier:child | 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; 10, 16; 10, 17; 10, 18; 11, 19; 13, 20; 13, 21; 14, 22; 14, 23; 15, 24; 15, 25; 17, 26; 17, 27; 18, 28; 19, 29; 19, 30; 21, 31; 21, 32; 25, 33; 25, 34; 27, 35; 28, 36; 28, 37; 30, 38; 32, 39; 33, 40; 36, 41; 36, 42; 37, 43; 37, 44; 37, 45; 38, 46; 40, 47; 41, 48; 41, 49; 42, 50; 43, 51; 44, 52; 45, 53; 45, 54; 51, 55; 51, 56; 52, 57; 52, 58; 54, 59; 54, 60; 54, 61; 55, 62; 55, 63; 58, 64; 59, 65; 60, 66; 61, 67; 61, 68; 61, 69; 65, 70; 65, 71; 66, 72; 66, 73; 67, 74; 67, 75; 68, 76; 68, 77; 69, 78; 71, 79; 71, 80; 73, 81; 73, 82; 74, 83; 74, 84; 75, 85; 75, 86; 76, 87; 77, 88; 78, 89; 78, 90; 78, 91; 80, 92; 86, 93; 87, 94; 87, 95; 88, 96; 88, 97; 89, 98; 90, 99; 91, 100; 91, 101; 94, 102; 94, 103; 96, 104; 96, 105; 97, 106; 98, 107; 98, 108; 99, 109; 99, 110; 100, 111; 100, 112; 101, 113; 101, 114; 108, 115; 108, 116; 109, 117; 109, 118; 111, 119; 111, 120; 112, 121; 113, 122; 114, 123; 116, 124; 116, 125; 122, 126; 122, 127; 123, 128; 123, 129; 126, 130; 126, 131; 128, 132; 128, 133; 129, 134 | def topological_order_dfs(graph):
"""Topological sorting by depth first search
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of vertices in order
:complexity: `O(|V|+|E|)`
"""
n = len(graph)
order = []
times_seen = [-1] * n
for start in range(n):
if times_seen[start] == -1:
times_seen[start] = 0
to_visit = [start]
while to_visit:
node = to_visit[-1]
children = graph[node]
if times_seen[node] == len(children):
to_visit.pop()
order.append(node)
else:
child = children[times_seen[node]]
times_seen[node] += 1
if times_seen[child] == -1:
times_seen[child] = 0
to_visit.append(child)
return order[::-1] |
0, module; 1, function_definition; 2, function_name:topological_order; 3, parameters; 4, block; 5, identifier:graph; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, expression_statement; 11, expression_statement; 12, while_statement; 13, return_statement; 14, comment:"""Topological sorting by maintaining indegree
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of vertices in order
:complexity: `O(|V|+|E|)`
"""; 15, assignment; 16, assignment; 17, identifier:node; 18, identifier:V; 19, comment:# compute indegree; 20, block; 21, assignment; 22, assignment; 23, identifier:Q; 24, block; 25, identifier:order; 26, identifier:V; 27, call; 28, identifier:indeg; 29, list_comprehension; 30, for_statement; 31, identifier:Q; 32, list_comprehension; 33, identifier:order; 34, list; 35, expression_statement; 36, comment:# node without incoming arrows; 37, expression_statement; 38, for_statement; 39, identifier:range; 40, argument_list; 41, integer:0; 42, for_in_clause; 43, identifier:neighbor; 44, subscript; 45, block; 46, identifier:node; 47, for_in_clause; 48, if_clause; 49, assignment; 50, call; 51, identifier:neighbor; 52, subscript; 53, block; 54, call; 55, identifier:_; 56, identifier:V; 57, identifier:graph; 58, identifier:node; 59, expression_statement; 60, identifier:node; 61, identifier:V; 62, comparison_operator:indeg[node] == 0; 63, identifier:node; 64, call; 65, attribute; 66, argument_list; 67, identifier:graph; 68, identifier:node; 69, expression_statement; 70, if_statement; 71, identifier:len; 72, argument_list; 73, augmented_assignment; 74, subscript; 75, integer:0; 76, attribute; 77, argument_list; 78, identifier:order; 79, identifier:append; 80, identifier:node; 81, augmented_assignment; 82, comparison_operator:indeg[neighbor] == 0; 83, block; 84, identifier:graph; 85, subscript; 86, integer:1; 87, identifier:indeg; 88, identifier:node; 89, identifier:Q; 90, identifier:pop; 91, subscript; 92, integer:1; 93, subscript; 94, integer:0; 95, expression_statement; 96, identifier:indeg; 97, identifier:neighbor; 98, identifier:indeg; 99, identifier:neighbor; 100, identifier:indeg; 101, identifier:neighbor; 102, call; 103, attribute; 104, argument_list; 105, identifier:Q; 106, identifier:append; 107, identifier:neighbor | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 6, 14; 7, 15; 8, 16; 9, 17; 9, 18; 9, 19; 9, 20; 10, 21; 11, 22; 12, 23; 12, 24; 13, 25; 15, 26; 15, 27; 16, 28; 16, 29; 20, 30; 21, 31; 21, 32; 22, 33; 22, 34; 24, 35; 24, 36; 24, 37; 24, 38; 27, 39; 27, 40; 29, 41; 29, 42; 30, 43; 30, 44; 30, 45; 32, 46; 32, 47; 32, 48; 35, 49; 37, 50; 38, 51; 38, 52; 38, 53; 40, 54; 42, 55; 42, 56; 44, 57; 44, 58; 45, 59; 47, 60; 47, 61; 48, 62; 49, 63; 49, 64; 50, 65; 50, 66; 52, 67; 52, 68; 53, 69; 53, 70; 54, 71; 54, 72; 59, 73; 62, 74; 62, 75; 64, 76; 64, 77; 65, 78; 65, 79; 66, 80; 69, 81; 70, 82; 70, 83; 72, 84; 73, 85; 73, 86; 74, 87; 74, 88; 76, 89; 76, 90; 81, 91; 81, 92; 82, 93; 82, 94; 83, 95; 85, 96; 85, 97; 91, 98; 91, 99; 93, 100; 93, 101; 95, 102; 102, 103; 102, 104; 103, 105; 103, 106; 104, 107 | def topological_order(graph):
"""Topological sorting by maintaining indegree
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of vertices in order
:complexity: `O(|V|+|E|)`
"""
V = range(len(graph))
indeg = [0 for _ in V]
for node in V: # compute indegree
for neighbor in graph[node]:
indeg[neighbor] += 1
Q = [node for node in V if indeg[node] == 0]
order = []
while Q:
node = Q.pop() # node without incoming arrows
order.append(node)
for neighbor in graph[node]:
indeg[neighbor] -= 1
if indeg[neighbor] == 0:
Q.append(neighbor)
return order |
0, module; 1, function_definition; 2, function_name:interval_tree; 3, parameters; 4, block; 5, identifier:intervals; 6, expression_statement; 7, if_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, for_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, return_statement; 18, comment:"""Construct an interval tree
:param intervals: list of half-open intervals
encoded as value pairs *[left, right)*
:assumes: intervals are lexicographically ordered
``>>> assert intervals == sorted(intervals)``
:returns: the root of the interval tree
:complexity: :math:`O(n)`
"""; 19, comparison_operator:intervals == []; 20, block; 21, assignment; 22, assignment; 23, assignment; 24, assignment; 25, identifier:I; 26, identifier:intervals; 27, block; 28, assignment; 29, assignment; 30, assignment; 31, assignment; 32, call; 33, identifier:intervals; 34, list; 35, return_statement; 36, identifier:center; 37, subscript; 38, identifier:L; 39, list; 40, identifier:R; 41, list; 42, identifier:C; 43, list; 44, if_statement; 45, identifier:by_low; 46, call; 47, identifier:by_high; 48, call; 49, identifier:IL; 50, call; 51, identifier:IR; 52, call; 53, identifier:_Node; 54, argument_list; 55, None; 56, subscript; 57, integer:0; 58, comparison_operator:I[1] <= center; 59, block; 60, elif_clause; 61, else_clause; 62, identifier:sorted; 63, generator_expression; 64, identifier:sorted; 65, generator_expression; 66, identifier:interval_tree; 67, argument_list; 68, identifier:interval_tree; 69, argument_list; 70, identifier:center; 71, identifier:by_low; 72, identifier:by_high; 73, identifier:IL; 74, identifier:IR; 75, identifier:intervals; 76, binary_operator:len(intervals) // 2; 77, subscript; 78, identifier:center; 79, expression_statement; 80, comparison_operator:center < I[0]; 81, block; 82, block; 83, tuple; 84, for_in_clause; 85, tuple; 86, for_in_clause; 87, identifier:L; 88, identifier:R; 89, call; 90, integer:2; 91, identifier:I; 92, integer:1; 93, call; 94, identifier:center; 95, subscript; 96, expression_statement; 97, expression_statement; 98, subscript; 99, identifier:I; 100, identifier:I; 101, identifier:C; 102, subscript; 103, identifier:I; 104, identifier:I; 105, identifier:C; 106, identifier:len; 107, argument_list; 108, attribute; 109, argument_list; 110, identifier:I; 111, integer:0; 112, call; 113, call; 114, identifier:I; 115, integer:0; 116, identifier:I; 117, integer:1; 118, identifier:intervals; 119, identifier:L; 120, identifier:append; 121, identifier:I; 122, attribute; 123, argument_list; 124, attribute; 125, argument_list; 126, identifier:R; 127, identifier:append; 128, identifier:I; 129, identifier:C; 130, identifier:append; 131, identifier:I | 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; 7, 20; 8, 21; 9, 22; 10, 23; 11, 24; 12, 25; 12, 26; 12, 27; 13, 28; 14, 29; 15, 30; 16, 31; 17, 32; 19, 33; 19, 34; 20, 35; 21, 36; 21, 37; 22, 38; 22, 39; 23, 40; 23, 41; 24, 42; 24, 43; 27, 44; 28, 45; 28, 46; 29, 47; 29, 48; 30, 49; 30, 50; 31, 51; 31, 52; 32, 53; 32, 54; 35, 55; 37, 56; 37, 57; 44, 58; 44, 59; 44, 60; 44, 61; 46, 62; 46, 63; 48, 64; 48, 65; 50, 66; 50, 67; 52, 68; 52, 69; 54, 70; 54, 71; 54, 72; 54, 73; 54, 74; 56, 75; 56, 76; 58, 77; 58, 78; 59, 79; 60, 80; 60, 81; 61, 82; 63, 83; 63, 84; 65, 85; 65, 86; 67, 87; 69, 88; 76, 89; 76, 90; 77, 91; 77, 92; 79, 93; 80, 94; 80, 95; 81, 96; 82, 97; 83, 98; 83, 99; 84, 100; 84, 101; 85, 102; 85, 103; 86, 104; 86, 105; 89, 106; 89, 107; 93, 108; 93, 109; 95, 110; 95, 111; 96, 112; 97, 113; 98, 114; 98, 115; 102, 116; 102, 117; 107, 118; 108, 119; 108, 120; 109, 121; 112, 122; 112, 123; 113, 124; 113, 125; 122, 126; 122, 127; 123, 128; 124, 129; 124, 130; 125, 131 | def interval_tree(intervals):
"""Construct an interval tree
:param intervals: list of half-open intervals
encoded as value pairs *[left, right)*
:assumes: intervals are lexicographically ordered
``>>> assert intervals == sorted(intervals)``
:returns: the root of the interval tree
:complexity: :math:`O(n)`
"""
if intervals == []:
return None
center = intervals[len(intervals) // 2][0]
L = []
R = []
C = []
for I in intervals:
if I[1] <= center:
L.append(I)
elif center < I[0]:
R.append(I)
else:
C.append(I)
by_low = sorted((I[0], I) for I in C)
by_high = sorted((I[1], I) for I in C)
IL = interval_tree(L)
IR = interval_tree(R)
return _Node(center, by_low, by_high, IL, IR) |
0, module; 1, function_definition; 2, function_name:get_type; 3, parameters; 4, block; 5, identifier:self; 6, identifier:name; 7, expression_statement; 8, comment:# XXX FIXME uhm...how to do all the different types of hidden-services?; 9, if_statement; 10, return_statement; 11, comment:"""
return the type of a config key.
:param: name the key
FIXME can we do something more-clever than this for client
code to determine what sort of thing a key is?
"""; 12, comparison_operator:name.lower() == 'hiddenservices'; 13, block; 14, call; 15, call; 16, string; 17, return_statement; 18, identifier:type; 19, argument_list; 20, attribute; 21, argument_list; 22, string_content:hiddenservices; 23, identifier:FilesystemOnionService; 24, subscript; 25, identifier:name; 26, identifier:lower; 27, attribute; 28, identifier:name; 29, identifier:self; 30, identifier:parsers | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 9, 12; 9, 13; 10, 14; 12, 15; 12, 16; 13, 17; 14, 18; 14, 19; 15, 20; 15, 21; 16, 22; 17, 23; 19, 24; 20, 25; 20, 26; 24, 27; 24, 28; 27, 29; 27, 30 | def get_type(self, name):
"""
return the type of a config key.
:param: name the key
FIXME can we do something more-clever than this for client
code to determine what sort of thing a key is?
"""
# XXX FIXME uhm...how to do all the different types of hidden-services?
if name.lower() == 'hiddenservices':
return FilesystemOnionService
return type(self.parsers[name]) |
0, module; 1, function_definition; 2, function_name:schwarz; 3, parameters; 4, block; 5, identifier:A; 6, identifier:x; 7, identifier:b; 8, default_parameter; 9, default_parameter; 10, default_parameter; 11, default_parameter; 12, default_parameter; 13, default_parameter; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, if_statement; 18, comment:# If no subdomains are defined, default is to use the sparsity pattern of A; 19, comment:# to define the overlapping regions; 20, expression_statement; 21, if_statement; 22, comment:# Call C code, need to make sure that subdomains are sorted and unique; 23, for_statement; 24, identifier:iterations; 25, integer:1; 26, identifier:subdomain; 27, None; 28, identifier:subdomain_ptr; 29, None; 30, identifier:inv_subblock; 31, None; 32, identifier:inv_subblock_ptr; 33, None; 34, identifier:sweep; 35, string; 36, comment:"""Perform Overlapping multiplicative Schwarz on the linear system Ax=b.
Parameters
----------
A : csr_matrix, bsr_matrix
Sparse NxN matrix
x : ndarray
Approximate solution (length N)
b : ndarray
Right-hand side (length N)
iterations : int
Number of iterations to perform
subdomain : int array
Linear array containing each subdomain's elements
subdomain_ptr : int array
Pointer in subdomain, such that
subdomain[subdomain_ptr[i]:subdomain_ptr[i+1]]]
contains the _sorted_ indices in subdomain i
inv_subblock : int_array
Linear array containing each subdomain's
inverted diagonal block of A
inv_subblock_ptr : int array
Pointer in inv_subblock, such that
inv_subblock[inv_subblock_ptr[i]:inv_subblock_ptr[i+1]]]
contains the inverted diagonal block of A for the
i-th subdomain in _row_ major order
sweep : {'forward','backward','symmetric'}
Direction of sweep
Returns
-------
Nothing, x will be modified in place.
Notes
-----
If subdomains is None, then a point-wise iteration takes place,
with the overlapping region defined by each degree-of-freedom's
neighbors in the matrix graph.
If subdomains is not None, but subblocks is, then the subblocks
are formed internally.
Currently only supports CSR matrices
Examples
--------
>>> # Use Overlapping Schwarz as a Stand-Alone Solver
>>> from pyamg.relaxation.relaxation import schwarz
>>> from pyamg.gallery import poisson
>>> from pyamg.util.linalg import norm
>>> import numpy as np
>>> A = poisson((10,10), format='csr')
>>> x0 = np.zeros((A.shape[0],1))
>>> b = np.ones((A.shape[0],1))
>>> schwarz(A, x0, b, iterations=10)
>>> print norm(b-A*x0)
0.126326160522
>>> #
>>> # Schwarz as the Multigrid Smoother
>>> from pyamg import smoothed_aggregation_solver
>>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)),
... coarse_solver='pinv2', max_coarse=50,
... presmoother='schwarz',
... postsmoother='schwarz')
>>> x0=np.zeros((A.shape[0],1))
>>> residuals=[]
>>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)
"""; 37, assignment; 38, call; 39, boolean_operator; 40, block; 41, assignment; 42, comparison_operator:sweep == 'forward'; 43, block; 44, elif_clause; 45, elif_clause; 46, else_clause; 47, identifier:iter; 48, call; 49, block; 50, string_content:forward; 51, pattern_list; 52, call; 53, attribute; 54, argument_list; 55, comparison_operator:subdomain is None; 56, comparison_operator:inv_subblock is not None; 57, raise_statement; 58, tuple_pattern; 59, line_continuation:\; 60, call; 61, identifier:sweep; 62, string; 63, expression_statement; 64, comparison_operator:sweep == 'backward'; 65, block; 66, comparison_operator:sweep == 'symmetric'; 67, block; 68, block; 69, identifier:range; 70, argument_list; 71, expression_statement; 72, identifier:A; 73, identifier:x; 74, identifier:b; 75, identifier:make_system; 76, argument_list; 77, identifier:A; 78, identifier:sort_indices; 79, identifier:subdomain; 80, None; 81, identifier:inv_subblock; 82, None; 83, call; 84, identifier:subdomain; 85, identifier:subdomain_ptr; 86, identifier:inv_subblock; 87, identifier:inv_subblock_ptr; 88, identifier:schwarz_parameters; 89, argument_list; 90, string_content:forward; 91, assignment; 92, identifier:sweep; 93, string; 94, expression_statement; 95, identifier:sweep; 96, string; 97, for_statement; 98, return_statement; 99, raise_statement; 100, identifier:iterations; 101, call; 102, identifier:A; 103, identifier:x; 104, identifier:b; 105, keyword_argument; 106, identifier:ValueError; 107, argument_list; 108, identifier:A; 109, identifier:subdomain; 110, identifier:subdomain_ptr; 111, identifier:inv_subblock; 112, identifier:inv_subblock_ptr; 113, pattern_list; 114, expression_list; 115, string_content:backward; 116, assignment; 117, string_content:symmetric; 118, identifier:iter; 119, call; 120, block; 121, call; 122, attribute; 123, argument_list; 124, identifier:formats; 125, list; 126, string:"inv_subblock must be None if subdomain is None"; 127, identifier:row_start; 128, identifier:row_stop; 129, identifier:row_step; 130, integer:0; 131, binary_operator:subdomain_ptr.shape[0]-1; 132, integer:1; 133, pattern_list; 134, expression_list; 135, identifier:range; 136, argument_list; 137, expression_statement; 138, expression_statement; 139, identifier:ValueError; 140, argument_list; 141, identifier:amg_core; 142, identifier:overlapping_schwarz_csr; 143, attribute; 144, attribute; 145, attribute; 146, identifier:x; 147, identifier:b; 148, identifier:inv_subblock; 149, identifier:inv_subblock_ptr; 150, identifier:subdomain; 151, identifier:subdomain_ptr; 152, binary_operator:subdomain_ptr.shape[0]-1; 153, subscript; 154, identifier:row_start; 155, identifier:row_stop; 156, identifier:row_step; 157, string; 158, subscript; 159, integer:1; 160, identifier:row_start; 161, identifier:row_stop; 162, identifier:row_step; 163, binary_operator:subdomain_ptr.shape[0]-2; 164, unary_operator; 165, unary_operator; 166, identifier:iterations; 167, call; 168, call; 169, string:"valid sweep directions are 'forward',\
'backward', and 'symmetric'"; 170, identifier:A; 171, identifier:indptr; 172, identifier:A; 173, identifier:indices; 174, identifier:A; 175, identifier:data; 176, subscript; 177, integer:1; 178, attribute; 179, integer:0; 180, string_content:csr; 181, attribute; 182, integer:0; 183, subscript; 184, integer:2; 185, integer:1; 186, integer:1; 187, identifier:schwarz; 188, argument_list; 189, identifier:schwarz; 190, argument_list; 191, attribute; 192, integer:0; 193, identifier:A; 194, identifier:shape; 195, identifier:subdomain_ptr; 196, identifier:shape; 197, attribute; 198, integer:0; 199, identifier:A; 200, identifier:x; 201, identifier:b; 202, keyword_argument; 203, keyword_argument; 204, keyword_argument; 205, keyword_argument; 206, keyword_argument; 207, keyword_argument; 208, identifier:A; 209, identifier:x; 210, identifier:b; 211, keyword_argument; 212, keyword_argument; 213, keyword_argument; 214, keyword_argument; 215, keyword_argument; 216, keyword_argument; 217, identifier:subdomain_ptr; 218, identifier:shape; 219, identifier:subdomain_ptr; 220, identifier:shape; 221, identifier:iterations; 222, integer:1; 223, identifier:subdomain; 224, identifier:subdomain; 225, identifier:subdomain_ptr; 226, identifier:subdomain_ptr; 227, identifier:inv_subblock; 228, identifier:inv_subblock; 229, identifier:inv_subblock_ptr; 230, identifier:inv_subblock_ptr; 231, identifier:sweep; 232, string; 233, identifier:iterations; 234, integer:1; 235, identifier:subdomain; 236, identifier:subdomain; 237, identifier:subdomain_ptr; 238, identifier:subdomain_ptr; 239, identifier:inv_subblock; 240, identifier:inv_subblock; 241, identifier:inv_subblock_ptr; 242, identifier:inv_subblock_ptr; 243, identifier:sweep; 244, string; 245, string_content:forward; 246, string_content:backward | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 4, 19; 4, 20; 4, 21; 4, 22; 4, 23; 8, 24; 8, 25; 9, 26; 9, 27; 10, 28; 10, 29; 11, 30; 11, 31; 12, 32; 12, 33; 13, 34; 13, 35; 14, 36; 15, 37; 16, 38; 17, 39; 17, 40; 20, 41; 21, 42; 21, 43; 21, 44; 21, 45; 21, 46; 23, 47; 23, 48; 23, 49; 35, 50; 37, 51; 37, 52; 38, 53; 38, 54; 39, 55; 39, 56; 40, 57; 41, 58; 41, 59; 41, 60; 42, 61; 42, 62; 43, 63; 44, 64; 44, 65; 45, 66; 45, 67; 46, 68; 48, 69; 48, 70; 49, 71; 51, 72; 51, 73; 51, 74; 52, 75; 52, 76; 53, 77; 53, 78; 55, 79; 55, 80; 56, 81; 56, 82; 57, 83; 58, 84; 58, 85; 58, 86; 58, 87; 60, 88; 60, 89; 62, 90; 63, 91; 64, 92; 64, 93; 65, 94; 66, 95; 66, 96; 67, 97; 67, 98; 68, 99; 70, 100; 71, 101; 76, 102; 76, 103; 76, 104; 76, 105; 83, 106; 83, 107; 89, 108; 89, 109; 89, 110; 89, 111; 89, 112; 91, 113; 91, 114; 93, 115; 94, 116; 96, 117; 97, 118; 97, 119; 97, 120; 99, 121; 101, 122; 101, 123; 105, 124; 105, 125; 107, 126; 113, 127; 113, 128; 113, 129; 114, 130; 114, 131; 114, 132; 116, 133; 116, 134; 119, 135; 119, 136; 120, 137; 120, 138; 121, 139; 121, 140; 122, 141; 122, 142; 123, 143; 123, 144; 123, 145; 123, 146; 123, 147; 123, 148; 123, 149; 123, 150; 123, 151; 123, 152; 123, 153; 123, 154; 123, 155; 123, 156; 125, 157; 131, 158; 131, 159; 133, 160; 133, 161; 133, 162; 134, 163; 134, 164; 134, 165; 136, 166; 137, 167; 138, 168; 140, 169; 143, 170; 143, 171; 144, 172; 144, 173; 145, 174; 145, 175; 152, 176; 152, 177; 153, 178; 153, 179; 157, 180; 158, 181; 158, 182; 163, 183; 163, 184; 164, 185; 165, 186; 167, 187; 167, 188; 168, 189; 168, 190; 176, 191; 176, 192; 178, 193; 178, 194; 181, 195; 181, 196; 183, 197; 183, 198; 188, 199; 188, 200; 188, 201; 188, 202; 188, 203; 188, 204; 188, 205; 188, 206; 188, 207; 190, 208; 190, 209; 190, 210; 190, 211; 190, 212; 190, 213; 190, 214; 190, 215; 190, 216; 191, 217; 191, 218; 197, 219; 197, 220; 202, 221; 202, 222; 203, 223; 203, 224; 204, 225; 204, 226; 205, 227; 205, 228; 206, 229; 206, 230; 207, 231; 207, 232; 211, 233; 211, 234; 212, 235; 212, 236; 213, 237; 213, 238; 214, 239; 214, 240; 215, 241; 215, 242; 216, 243; 216, 244; 232, 245; 244, 246 | def schwarz(A, x, b, iterations=1, subdomain=None, subdomain_ptr=None,
inv_subblock=None, inv_subblock_ptr=None, sweep='forward'):
"""Perform Overlapping multiplicative Schwarz on the linear system Ax=b.
Parameters
----------
A : csr_matrix, bsr_matrix
Sparse NxN matrix
x : ndarray
Approximate solution (length N)
b : ndarray
Right-hand side (length N)
iterations : int
Number of iterations to perform
subdomain : int array
Linear array containing each subdomain's elements
subdomain_ptr : int array
Pointer in subdomain, such that
subdomain[subdomain_ptr[i]:subdomain_ptr[i+1]]]
contains the _sorted_ indices in subdomain i
inv_subblock : int_array
Linear array containing each subdomain's
inverted diagonal block of A
inv_subblock_ptr : int array
Pointer in inv_subblock, such that
inv_subblock[inv_subblock_ptr[i]:inv_subblock_ptr[i+1]]]
contains the inverted diagonal block of A for the
i-th subdomain in _row_ major order
sweep : {'forward','backward','symmetric'}
Direction of sweep
Returns
-------
Nothing, x will be modified in place.
Notes
-----
If subdomains is None, then a point-wise iteration takes place,
with the overlapping region defined by each degree-of-freedom's
neighbors in the matrix graph.
If subdomains is not None, but subblocks is, then the subblocks
are formed internally.
Currently only supports CSR matrices
Examples
--------
>>> # Use Overlapping Schwarz as a Stand-Alone Solver
>>> from pyamg.relaxation.relaxation import schwarz
>>> from pyamg.gallery import poisson
>>> from pyamg.util.linalg import norm
>>> import numpy as np
>>> A = poisson((10,10), format='csr')
>>> x0 = np.zeros((A.shape[0],1))
>>> b = np.ones((A.shape[0],1))
>>> schwarz(A, x0, b, iterations=10)
>>> print norm(b-A*x0)
0.126326160522
>>> #
>>> # Schwarz as the Multigrid Smoother
>>> from pyamg import smoothed_aggregation_solver
>>> sa = smoothed_aggregation_solver(A, B=np.ones((A.shape[0],1)),
... coarse_solver='pinv2', max_coarse=50,
... presmoother='schwarz',
... postsmoother='schwarz')
>>> x0=np.zeros((A.shape[0],1))
>>> residuals=[]
>>> x = sa.solve(b, x0=x0, tol=1e-8, residuals=residuals)
"""
A, x, b = make_system(A, x, b, formats=['csr'])
A.sort_indices()
if subdomain is None and inv_subblock is not None:
raise ValueError("inv_subblock must be None if subdomain is None")
# If no subdomains are defined, default is to use the sparsity pattern of A
# to define the overlapping regions
(subdomain, subdomain_ptr, inv_subblock, inv_subblock_ptr) = \
schwarz_parameters(A, subdomain, subdomain_ptr,
inv_subblock, inv_subblock_ptr)
if sweep == 'forward':
row_start, row_stop, row_step = 0, subdomain_ptr.shape[0]-1, 1
elif sweep == 'backward':
row_start, row_stop, row_step = subdomain_ptr.shape[0]-2, -1, -1
elif sweep == 'symmetric':
for iter in range(iterations):
schwarz(A, x, b, iterations=1, subdomain=subdomain,
subdomain_ptr=subdomain_ptr, inv_subblock=inv_subblock,
inv_subblock_ptr=inv_subblock_ptr, sweep='forward')
schwarz(A, x, b, iterations=1, subdomain=subdomain,
subdomain_ptr=subdomain_ptr, inv_subblock=inv_subblock,
inv_subblock_ptr=inv_subblock_ptr, sweep='backward')
return
else:
raise ValueError("valid sweep directions are 'forward',\
'backward', and 'symmetric'")
# Call C code, need to make sure that subdomains are sorted and unique
for iter in range(iterations):
amg_core.overlapping_schwarz_csr(A.indptr, A.indices, A.data,
x, b, inv_subblock, inv_subblock_ptr,
subdomain, subdomain_ptr,
subdomain_ptr.shape[0]-1, A.shape[0],
row_start, row_stop, row_step) |
0, module; 1, function_definition; 2, function_name:get_stdlib_path; 3, parameters; 4, block; 5, expression_statement; 6, if_statement; 7, comment:"""Returns the path to the standard lib for the current path installation.
This function can be dropped and "sysconfig.get_paths()" used directly once Python 2.6 support is dropped.
"""; 8, comparison_operator:sys.version_info >= (2, 7); 9, block; 10, else_clause; 11, attribute; 12, tuple; 13, import_statement; 14, return_statement; 15, block; 16, identifier:sys; 17, identifier:version_info; 18, integer:2; 19, integer:7; 20, dotted_name; 21, subscript; 22, return_statement; 23, identifier:sysconfig; 24, call; 25, string; 26, call; 27, attribute; 28, argument_list; 29, string_content:stdlib; 30, attribute; 31, argument_list; 32, identifier:sysconfig; 33, identifier:get_paths; 34, attribute; 35, identifier:join; 36, attribute; 37, string; 38, identifier:os; 39, identifier:path; 40, identifier:sys; 41, identifier:prefix; 42, string_content:lib | 0, 1; 1, 2; 1, 3; 1, 4; 4, 5; 4, 6; 5, 7; 6, 8; 6, 9; 6, 10; 8, 11; 8, 12; 9, 13; 9, 14; 10, 15; 11, 16; 11, 17; 12, 18; 12, 19; 13, 20; 14, 21; 15, 22; 20, 23; 21, 24; 21, 25; 22, 26; 24, 27; 24, 28; 25, 29; 26, 30; 26, 31; 27, 32; 27, 33; 30, 34; 30, 35; 31, 36; 31, 37; 34, 38; 34, 39; 36, 40; 36, 41; 37, 42 | def get_stdlib_path():
"""Returns the path to the standard lib for the current path installation.
This function can be dropped and "sysconfig.get_paths()" used directly once Python 2.6 support is dropped.
"""
if sys.version_info >= (2, 7):
import sysconfig
return sysconfig.get_paths()['stdlib']
else:
return os.path.join(sys.prefix, 'lib') |
0, module; 1, function_definition; 2, function_name:exists_case_sensitive; 3, parameters; 4, block; 5, identifier:path; 6, expression_statement; 7, expression_statement; 8, if_statement; 9, return_statement; 10, comment:"""
Returns if the given path exists and also matches the case on Windows.
When finding files that can be imported, it is important for the cases to match because while
file os.path.exists("module.py") and os.path.exists("MODULE.py") both return True on Windows, Python
can only import using the case of the real file.
"""; 11, assignment; 12, boolean_operator; 13, block; 14, identifier:result; 15, identifier:result; 16, call; 17, call; 18, identifier:result; 19, expression_statement; 20, expression_statement; 21, attribute; 22, argument_list; 23, attribute; 24, argument_list; 25, assignment; 26, assignment; 27, attribute; 28, identifier:exists; 29, identifier:path; 30, attribute; 31, identifier:startswith; 32, string; 33, pattern_list; 34, call; 35, identifier:result; 36, comparison_operator:basename in os.listdir(directory); 37, identifier:os; 38, identifier:path; 39, identifier:sys; 40, identifier:platform; 41, string_content:win; 42, identifier:directory; 43, identifier:basename; 44, attribute; 45, argument_list; 46, identifier:basename; 47, call; 48, attribute; 49, identifier:split; 50, identifier:path; 51, attribute; 52, argument_list; 53, identifier:os; 54, identifier:path; 55, identifier:os; 56, identifier:listdir; 57, identifier:directory | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 8, 13; 9, 14; 11, 15; 11, 16; 12, 17; 12, 18; 13, 19; 13, 20; 16, 21; 16, 22; 17, 23; 17, 24; 19, 25; 20, 26; 21, 27; 21, 28; 22, 29; 23, 30; 23, 31; 24, 32; 25, 33; 25, 34; 26, 35; 26, 36; 27, 37; 27, 38; 30, 39; 30, 40; 32, 41; 33, 42; 33, 43; 34, 44; 34, 45; 36, 46; 36, 47; 44, 48; 44, 49; 45, 50; 47, 51; 47, 52; 48, 53; 48, 54; 51, 55; 51, 56; 52, 57 | def exists_case_sensitive(path):
"""
Returns if the given path exists and also matches the case on Windows.
When finding files that can be imported, it is important for the cases to match because while
file os.path.exists("module.py") and os.path.exists("MODULE.py") both return True on Windows, Python
can only import using the case of the real file.
"""
result = os.path.exists(path)
if sys.platform.startswith('win') and result:
directory, basename = os.path.split(path)
result = basename in os.listdir(directory)
return result |
0, module; 1, function_definition; 2, function_name:_add_comments; 3, parameters; 4, block; 5, identifier:self; 6, identifier:comments; 7, default_parameter; 8, expression_statement; 9, return_statement; 10, identifier:original_string; 11, string:""; 12, comment:"""
Returns a string with comments added
"""; 13, boolean_operator; 14, boolean_operator; 15, identifier:original_string; 16, identifier:comments; 17, call; 18, attribute; 19, argument_list; 20, string:"{0} # {1}"; 21, identifier:format; 22, subscript; 23, call; 24, call; 25, integer:0; 26, attribute; 27, argument_list; 28, attribute; 29, argument_list; 30, string:"; "; 31, identifier:join; 32, identifier:comments; 33, identifier:self; 34, identifier:_strip_comments; 35, identifier:original_string | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 7, 10; 7, 11; 8, 12; 9, 13; 13, 14; 13, 15; 14, 16; 14, 17; 17, 18; 17, 19; 18, 20; 18, 21; 19, 22; 19, 23; 22, 24; 22, 25; 23, 26; 23, 27; 24, 28; 24, 29; 26, 30; 26, 31; 27, 32; 28, 33; 28, 34; 29, 35 | def _add_comments(self, comments, original_string=""):
"""
Returns a string with comments added
"""
return comments and "{0} # {1}".format(self._strip_comments(original_string)[0],
"; ".join(comments)) or original_string |
0, module; 1, function_definition; 2, function_name:_priority_key; 3, parameters; 4, block; 5, identifier:pep8_result; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, try_statement; 12, comment:"""Key for sorting PEP8 results.
Global fixes should be done first. This is important for things like
indentation.
"""; 13, assignment; 14, assignment; 15, assignment; 16, assignment; 17, block; 18, except_clause; 19, identifier:priority; 20, list; 21, identifier:middle_index; 22, integer:10000; 23, identifier:lowest_priority; 24, list; 25, identifier:key; 26, call; 27, return_statement; 28, identifier:ValueError; 29, block; 30, comment:# Fix multiline colon-based before semicolon based.; 31, string; 32, comment:# Break multiline statements early.; 33, string; 34, comment:# Things that make lines longer.; 35, string; 36, string; 37, comment:# Remove extraneous whitespace before breaking lines.; 38, string; 39, comment:# Shorten whitespace in comment before resorting to wrapping.; 40, string; 41, comment:# We need to shorten lines last since the logical fixer can get in a; 42, comment:# loop, which causes us to exit early.; 43, string; 44, attribute; 45, argument_list; 46, call; 47, try_statement; 48, string_content:e701; 49, string_content:e702; 50, string_content:e225; 51, string_content:e231; 52, string_content:e201; 53, string_content:e262; 54, string_content:e501; 55, subscript; 56, identifier:lower; 57, attribute; 58, argument_list; 59, block; 60, except_clause; 61, identifier:pep8_result; 62, string; 63, identifier:priority; 64, identifier:index; 65, identifier:key; 66, return_statement; 67, identifier:ValueError; 68, block; 69, string_content:id; 70, binary_operator:middle_index + lowest_priority.index(key) + 1; 71, return_statement; 72, binary_operator:middle_index + lowest_priority.index(key); 73, integer:1; 74, identifier:middle_index; 75, identifier:middle_index; 76, call; 77, attribute; 78, argument_list; 79, identifier:lowest_priority; 80, identifier:index; 81, identifier:key | 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; 10, 16; 11, 17; 11, 18; 13, 19; 13, 20; 14, 21; 14, 22; 15, 23; 15, 24; 16, 25; 16, 26; 17, 27; 18, 28; 18, 29; 20, 30; 20, 31; 20, 32; 20, 33; 20, 34; 20, 35; 20, 36; 20, 37; 20, 38; 20, 39; 20, 40; 24, 41; 24, 42; 24, 43; 26, 44; 26, 45; 27, 46; 29, 47; 31, 48; 33, 49; 35, 50; 36, 51; 38, 52; 40, 53; 43, 54; 44, 55; 44, 56; 46, 57; 46, 58; 47, 59; 47, 60; 55, 61; 55, 62; 57, 63; 57, 64; 58, 65; 59, 66; 60, 67; 60, 68; 62, 69; 66, 70; 68, 71; 70, 72; 70, 73; 71, 74; 72, 75; 72, 76; 76, 77; 76, 78; 77, 79; 77, 80; 78, 81 | def _priority_key(pep8_result):
"""Key for sorting PEP8 results.
Global fixes should be done first. This is important for things like
indentation.
"""
priority = [
# Fix multiline colon-based before semicolon based.
'e701',
# Break multiline statements early.
'e702',
# Things that make lines longer.
'e225', 'e231',
# Remove extraneous whitespace before breaking lines.
'e201',
# Shorten whitespace in comment before resorting to wrapping.
'e262'
]
middle_index = 10000
lowest_priority = [
# We need to shorten lines last since the logical fixer can get in a
# loop, which causes us to exit early.
'e501'
]
key = pep8_result['id'].lower()
try:
return priority.index(key)
except ValueError:
try:
return middle_index + lowest_priority.index(key) + 1
except ValueError:
return middle_index |
0, module; 1, function_definition; 2, function_name:git_hook; 3, parameters; 4, block; 5, default_parameter; 6, expression_statement; 7, comment:# Get list of files modified and staged; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, return_statement; 13, identifier:strict; 14, False; 15, comment:"""
Git pre-commit hook to check staged files for isort errors
:param bool strict - if True, return number of errors on exit,
causing the hook to fail. If False, return zero so it will
just act as a warning.
:return number of errors if in strict mode, 0 otherwise.
"""; 16, assignment; 17, assignment; 18, assignment; 19, identifier:filename; 20, identifier:files_modified; 21, block; 22, conditional_expression:errors if strict else 0; 23, identifier:diff_cmd; 24, string:"git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD"; 25, identifier:files_modified; 26, call; 27, identifier:errors; 28, integer:0; 29, if_statement; 30, identifier:errors; 31, identifier:strict; 32, integer:0; 33, identifier:get_lines; 34, argument_list; 35, call; 36, comment:# Get the staged contents of the file; 37, block; 38, identifier:diff_cmd; 39, attribute; 40, argument_list; 41, expression_statement; 42, expression_statement; 43, expression_statement; 44, if_statement; 45, identifier:filename; 46, identifier:endswith; 47, string; 48, assignment; 49, assignment; 50, assignment; 51, attribute; 52, block; 53, string_content:.py; 54, identifier:staged_cmd; 55, binary_operator:"git show :%s" % filename; 56, identifier:staged_contents; 57, call; 58, identifier:sort; 59, call; 60, identifier:sort; 61, identifier:incorrectly_sorted; 62, expression_statement; 63, string:"git show :%s"; 64, identifier:filename; 65, identifier:get_output; 66, argument_list; 67, identifier:SortImports; 68, argument_list; 69, augmented_assignment; 70, identifier:staged_cmd; 71, keyword_argument; 72, keyword_argument; 73, keyword_argument; 74, identifier:errors; 75, integer:1; 76, identifier:file_path; 77, identifier:filename; 78, identifier:file_contents; 79, call; 80, identifier:check; 81, True; 82, attribute; 83, argument_list; 84, identifier:staged_contents; 85, identifier:decode | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 5, 13; 5, 14; 6, 15; 8, 16; 9, 17; 10, 18; 11, 19; 11, 20; 11, 21; 12, 22; 16, 23; 16, 24; 17, 25; 17, 26; 18, 27; 18, 28; 21, 29; 22, 30; 22, 31; 22, 32; 26, 33; 26, 34; 29, 35; 29, 36; 29, 37; 34, 38; 35, 39; 35, 40; 37, 41; 37, 42; 37, 43; 37, 44; 39, 45; 39, 46; 40, 47; 41, 48; 42, 49; 43, 50; 44, 51; 44, 52; 47, 53; 48, 54; 48, 55; 49, 56; 49, 57; 50, 58; 50, 59; 51, 60; 51, 61; 52, 62; 55, 63; 55, 64; 57, 65; 57, 66; 59, 67; 59, 68; 62, 69; 66, 70; 68, 71; 68, 72; 68, 73; 69, 74; 69, 75; 71, 76; 71, 77; 72, 78; 72, 79; 73, 80; 73, 81; 79, 82; 79, 83; 82, 84; 82, 85 | def git_hook(strict=False):
"""
Git pre-commit hook to check staged files for isort errors
:param bool strict - if True, return number of errors on exit,
causing the hook to fail. If False, return zero so it will
just act as a warning.
:return number of errors if in strict mode, 0 otherwise.
"""
# Get list of files modified and staged
diff_cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD"
files_modified = get_lines(diff_cmd)
errors = 0
for filename in files_modified:
if filename.endswith('.py'):
# Get the staged contents of the file
staged_cmd = "git show :%s" % filename
staged_contents = get_output(staged_cmd)
sort = SortImports(
file_path=filename,
file_contents=staged_contents.decode(),
check=True
)
if sort.incorrectly_sorted:
errors += 1
return errors if strict else 0 |
0, module; 1, function_definition; 2, function_name:get_all_fix_names; 3, parameters; 4, block; 5, identifier:fixer_pkg; 6, default_parameter; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, return_statement; 13, identifier:remove_prefix; 14, True; 15, comment:"""Return a sorted list of all available fix names in the given package."""; 16, assignment; 17, assignment; 18, assignment; 19, identifier:name; 20, call; 21, block; 22, identifier:fix_names; 23, identifier:pkg; 24, call; 25, identifier:fixer_dir; 26, call; 27, identifier:fix_names; 28, list; 29, identifier:sorted; 30, argument_list; 31, if_statement; 32, identifier:__import__; 33, argument_list; 34, attribute; 35, argument_list; 36, call; 37, boolean_operator; 38, block; 39, identifier:fixer_pkg; 40, list; 41, list; 42, list; 43, attribute; 44, identifier:dirname; 45, attribute; 46, attribute; 47, argument_list; 48, call; 49, call; 50, if_statement; 51, expression_statement; 52, string:"*"; 53, identifier:os; 54, identifier:path; 55, identifier:pkg; 56, identifier:__file__; 57, identifier:os; 58, identifier:listdir; 59, identifier:fixer_dir; 60, attribute; 61, argument_list; 62, attribute; 63, argument_list; 64, identifier:remove_prefix; 65, block; 66, call; 67, identifier:name; 68, identifier:startswith; 69, string:"fix_"; 70, identifier:name; 71, identifier:endswith; 72, string:".py"; 73, expression_statement; 74, attribute; 75, argument_list; 76, assignment; 77, identifier:fix_names; 78, identifier:append; 79, subscript; 80, identifier:name; 81, subscript; 82, identifier:name; 83, slice; 84, identifier:name; 85, slice; 86, unary_operator; 87, integer:4; 88, integer:3 | 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; 11, 19; 11, 20; 11, 21; 12, 22; 16, 23; 16, 24; 17, 25; 17, 26; 18, 27; 18, 28; 20, 29; 20, 30; 21, 31; 24, 32; 24, 33; 26, 34; 26, 35; 30, 36; 31, 37; 31, 38; 33, 39; 33, 40; 33, 41; 33, 42; 34, 43; 34, 44; 35, 45; 36, 46; 36, 47; 37, 48; 37, 49; 38, 50; 38, 51; 42, 52; 43, 53; 43, 54; 45, 55; 45, 56; 46, 57; 46, 58; 47, 59; 48, 60; 48, 61; 49, 62; 49, 63; 50, 64; 50, 65; 51, 66; 60, 67; 60, 68; 61, 69; 62, 70; 62, 71; 63, 72; 65, 73; 66, 74; 66, 75; 73, 76; 74, 77; 74, 78; 75, 79; 76, 80; 76, 81; 79, 82; 79, 83; 81, 84; 81, 85; 83, 86; 85, 87; 86, 88 | def get_all_fix_names(fixer_pkg, remove_prefix=True):
"""Return a sorted list of all available fix names in the given package."""
pkg = __import__(fixer_pkg, [], [], ["*"])
fixer_dir = os.path.dirname(pkg.__file__)
fix_names = []
for name in sorted(os.listdir(fixer_dir)):
if name.startswith("fix_") and name.endswith(".py"):
if remove_prefix:
name = name[4:]
fix_names.append(name[:-3])
return fix_names |
0, module; 1, function_definition; 2, function_name:check; 3, parameters; 4, comment:# pragma: no cover; 5, block; 6, identifier:self; 7, expression_statement; 8, for_statement; 9, comment:"""re-sort any items in self that are not sorted"""; 10, identifier:unsorted; 11, call; 12, block; 13, identifier:iter; 14, generator_expression; 15, expression_statement; 16, subscript; 17, for_in_clause; 18, if_clause; 19, call; 20, identifier:self; 21, identifier:i; 22, identifier:i; 23, call; 24, not_operator; 25, attribute; 26, argument_list; 27, identifier:range; 28, argument_list; 29, call; 30, identifier:self; 31, identifier:resort; 32, identifier:unsorted; 33, binary_operator:len(self) - 2; 34, attribute; 35, argument_list; 36, call; 37, integer:2; 38, identifier:operator; 39, identifier:le; 40, subscript; 41, subscript; 42, identifier:len; 43, argument_list; 44, identifier:self; 45, identifier:i; 46, identifier:self; 47, binary_operator:i + 1; 48, identifier:self; 49, identifier:i; 50, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 1, 5; 3, 6; 5, 7; 5, 8; 7, 9; 8, 10; 8, 11; 8, 12; 11, 13; 11, 14; 12, 15; 14, 16; 14, 17; 14, 18; 15, 19; 16, 20; 16, 21; 17, 22; 17, 23; 18, 24; 19, 25; 19, 26; 23, 27; 23, 28; 24, 29; 25, 30; 25, 31; 26, 32; 28, 33; 29, 34; 29, 35; 33, 36; 33, 37; 34, 38; 34, 39; 35, 40; 35, 41; 36, 42; 36, 43; 40, 44; 40, 45; 41, 46; 41, 47; 43, 48; 47, 49; 47, 50 | def check(self): # pragma: no cover
"""re-sort any items in self that are not sorted"""
for unsorted in iter(self[i] for i in range(len(self) - 2) if not operator.le(self[i], self[i + 1])):
self.resort(unsorted) |
0, module; 1, function_definition; 2, function_name:sort_by_list_order; 3, parameters; 4, block; 5, identifier:sortlist; 6, identifier:reflist; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, function_definition; 12, if_statement; 13, return_statement; 14, identifier:reverse; 15, False; 16, identifier:fltr; 17, False; 18, identifier:slemap; 19, None; 20, comment:"""
Sort a list according to the order of entries in a reference list.
Parameters
----------
sortlist : list
List to be sorted
reflist : list
Reference list defining sorting order
reverse : bool, optional (default False)
Flag indicating whether to sort in reverse order
fltr : bool, optional (default False)
Flag indicating whether to filter `sortlist` to remove any entries
that are not in `reflist`
slemap : function or None, optional (default None)
Function mapping a sortlist entry to the form of an entry in
`reflist`
Returns
-------
sortedlist : list
Sorted (and possibly filtered) version of sortlist
"""; 21, function_name:keyfunc; 22, parameters; 23, block; 24, identifier:fltr; 25, block; 26, call; 27, identifier:entry; 28, if_statement; 29, if_statement; 30, if_statement; 31, identifier:sorted; 32, argument_list; 33, comparison_operator:slemap is not None; 34, block; 35, comparison_operator:rle in reflist; 36, comment:# Ordering index taken from reflist; 37, block; 38, else_clause; 39, identifier:slemap; 40, block; 41, else_clause; 42, identifier:sortlist; 43, keyword_argument; 44, keyword_argument; 45, identifier:slemap; 46, None; 47, expression_statement; 48, identifier:rle; 49, identifier:reflist; 50, return_statement; 51, comment:# Ordering index taken from sortlist, offset; 52, comment:# by the length of reflist so that entries; 53, comment:# that are not in reflist retain their order; 54, comment:# in sortlist; 55, block; 56, expression_statement; 57, block; 58, identifier:key; 59, identifier:keyfunc; 60, identifier:reverse; 61, identifier:reverse; 62, assignment; 63, call; 64, return_statement; 65, assignment; 66, expression_statement; 67, identifier:rle; 68, call; 69, attribute; 70, argument_list; 71, binary_operator:sortlist.index(entry) + len(reflist); 72, identifier:sortlist; 73, call; 74, assignment; 75, identifier:slemap; 76, argument_list; 77, identifier:reflist; 78, identifier:index; 79, identifier:rle; 80, call; 81, call; 82, identifier:filter; 83, argument_list; 84, identifier:sortlist; 85, call; 86, identifier:entry; 87, attribute; 88, argument_list; 89, identifier:len; 90, argument_list; 91, lambda; 92, identifier:sortlist; 93, identifier:filter; 94, argument_list; 95, identifier:sortlist; 96, identifier:index; 97, identifier:entry; 98, identifier:reflist; 99, lambda_parameters; 100, comparison_operator:slemap(x) in reflist; 101, lambda; 102, identifier:sortlist; 103, identifier:x; 104, call; 105, identifier:reflist; 106, lambda_parameters; 107, comparison_operator:x in reflist; 108, identifier:slemap; 109, argument_list; 110, identifier:x; 111, identifier:x; 112, identifier:reflist; 113, identifier:x | 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; 7, 14; 7, 15; 8, 16; 8, 17; 9, 18; 9, 19; 10, 20; 11, 21; 11, 22; 11, 23; 12, 24; 12, 25; 13, 26; 22, 27; 23, 28; 23, 29; 25, 30; 26, 31; 26, 32; 28, 33; 28, 34; 29, 35; 29, 36; 29, 37; 29, 38; 30, 39; 30, 40; 30, 41; 32, 42; 32, 43; 32, 44; 33, 45; 33, 46; 34, 47; 35, 48; 35, 49; 37, 50; 38, 51; 38, 52; 38, 53; 38, 54; 38, 55; 40, 56; 41, 57; 43, 58; 43, 59; 44, 60; 44, 61; 47, 62; 50, 63; 55, 64; 56, 65; 57, 66; 62, 67; 62, 68; 63, 69; 63, 70; 64, 71; 65, 72; 65, 73; 66, 74; 68, 75; 68, 76; 69, 77; 69, 78; 70, 79; 71, 80; 71, 81; 73, 82; 73, 83; 74, 84; 74, 85; 76, 86; 80, 87; 80, 88; 81, 89; 81, 90; 83, 91; 83, 92; 85, 93; 85, 94; 87, 95; 87, 96; 88, 97; 90, 98; 91, 99; 91, 100; 94, 101; 94, 102; 99, 103; 100, 104; 100, 105; 101, 106; 101, 107; 104, 108; 104, 109; 106, 110; 107, 111; 107, 112; 109, 113 | def sort_by_list_order(sortlist, reflist, reverse=False, fltr=False,
slemap=None):
"""
Sort a list according to the order of entries in a reference list.
Parameters
----------
sortlist : list
List to be sorted
reflist : list
Reference list defining sorting order
reverse : bool, optional (default False)
Flag indicating whether to sort in reverse order
fltr : bool, optional (default False)
Flag indicating whether to filter `sortlist` to remove any entries
that are not in `reflist`
slemap : function or None, optional (default None)
Function mapping a sortlist entry to the form of an entry in
`reflist`
Returns
-------
sortedlist : list
Sorted (and possibly filtered) version of sortlist
"""
def keyfunc(entry):
if slemap is not None:
rle = slemap(entry)
if rle in reflist:
# Ordering index taken from reflist
return reflist.index(rle)
else:
# Ordering index taken from sortlist, offset
# by the length of reflist so that entries
# that are not in reflist retain their order
# in sortlist
return sortlist.index(entry) + len(reflist)
if fltr:
if slemap:
sortlist = filter(lambda x: slemap(x) in reflist, sortlist)
else:
sortlist = filter(lambda x: x in reflist, sortlist)
return sorted(sortlist, key=keyfunc, reverse=reverse) |
0, module; 1, function_definition; 2, function_name:strategy; 3, parameters; 4, block; 5, identifier:self; 6, list_splat_pattern; 7, dictionary_splat_pattern; 8, expression_statement; 9, function_definition; 10, return_statement; 11, identifier:names; 12, identifier:kwargs; 13, comment:"""
StrategyDict wrapping method for adding a new strategy.
Parameters
----------
*names :
Positional arguments with all names (strings) that could be used to
call the strategy to be added, to be used both as key items and as
attribute names.
keep_name :
Boolean keyword-only parameter for choosing whether the ``__name__``
attribute of the decorated/wrapped function should be changed or kept.
Defaults to False (i.e., changes the name by default).
Returns
-------
A decorator/wrapper function to be used once on the new strategy to be
added.
Example
-------
Let's create a StrategyDict that knows its name:
>>> txt_proc = StrategyDict("txt_proc")
Add a first strategy ``swapcase``, using this method as a decorator
factory:
>>> @txt_proc.strategy("swapcase")
... def txt_proc(txt):
... return txt.swapcase()
Let's do it again, but wrapping the strategy functions inline. First two
strategies have multiple names, the last keeps the function name, which
would otherwise be replaced by the first given name:
>>> txt_proc.strategy("lower", "low")(lambda txt: txt.lower())
{(...): <function ... at 0x...>, (...): <function ... at 0x...>}
>>> txt_proc.strategy("upper", "up")(lambda txt: txt.upper())
{...}
>>> txt_proc.strategy("keep", keep_name=True)(lambda txt: txt)
{...}
We can now iterate through the strategies to call them or see their
function names
>>> sorted(st("Just a Test") for st in txt_proc)
['JUST A TEST', 'Just a Test', 'jUST A tEST', 'just a test']
>>> sorted(st.__name__ for st in txt_proc) # Just the first name
['<lambda>', 'lower', 'swapcase', 'upper']
Calling a single strategy:
>>> txt_proc.low("TeStInG")
'testing'
>>> txt_proc["upper"]("TeStInG")
'TESTING'
>>> txt_proc("TeStInG") # Default is the first: swapcase
'tEsTiNg'
>>> txt_proc.default("TeStInG")
'tEsTiNg'
>>> txt_proc.default = txt_proc.up # Manually changing the default
>>> txt_proc("TeStInG")
'TESTING'
Hint
----
Default strategy is the one stored as the ``default`` attribute, you can
change or remove it at any time. When removing all keys that are assigned
to the default strategy, the default attribute will be removed from the
StrategyDict instance as well. The first strategy added afterwards is the
one that will become the new default, unless the attribute is created or
changed manually.
"""; 14, function_name:decorator; 15, parameters; 16, block; 17, identifier:decorator; 18, identifier:func; 19, expression_statement; 20, if_statement; 21, if_statement; 22, expression_statement; 23, return_statement; 24, assignment; 25, identifier:kwargs; 26, block; 27, not_operator; 28, block; 29, assignment; 30, identifier:self; 31, identifier:keep_name; 32, call; 33, expression_statement; 34, raise_statement; 35, identifier:keep_name; 36, expression_statement; 37, subscript; 38, identifier:func; 39, attribute; 40, argument_list; 41, assignment; 42, call; 43, assignment; 44, identifier:self; 45, identifier:names; 46, identifier:kwargs; 47, identifier:pop; 48, string:"keep_name"; 49, False; 50, identifier:key; 51, call; 52, identifier:TypeError; 53, argument_list; 54, attribute; 55, call; 56, identifier:next; 57, argument_list; 58, call; 59, identifier:func; 60, identifier:__name__; 61, identifier:str; 62, argument_list; 63, call; 64, attribute; 65, argument_list; 66, subscript; 67, identifier:iter; 68, argument_list; 69, string:"Unknown keyword argument '{}'"; 70, identifier:format; 71, identifier:key; 72, identifier:names; 73, integer:0; 74, identifier:kwargs | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 6, 11; 7, 12; 8, 13; 9, 14; 9, 15; 9, 16; 10, 17; 15, 18; 16, 19; 16, 20; 16, 21; 16, 22; 16, 23; 19, 24; 20, 25; 20, 26; 21, 27; 21, 28; 22, 29; 23, 30; 24, 31; 24, 32; 26, 33; 26, 34; 27, 35; 28, 36; 29, 37; 29, 38; 32, 39; 32, 40; 33, 41; 34, 42; 36, 43; 37, 44; 37, 45; 39, 46; 39, 47; 40, 48; 40, 49; 41, 50; 41, 51; 42, 52; 42, 53; 43, 54; 43, 55; 51, 56; 51, 57; 53, 58; 54, 59; 54, 60; 55, 61; 55, 62; 57, 63; 58, 64; 58, 65; 62, 66; 63, 67; 63, 68; 64, 69; 64, 70; 65, 71; 66, 72; 66, 73; 68, 74 | def strategy(self, *names, **kwargs):
"""
StrategyDict wrapping method for adding a new strategy.
Parameters
----------
*names :
Positional arguments with all names (strings) that could be used to
call the strategy to be added, to be used both as key items and as
attribute names.
keep_name :
Boolean keyword-only parameter for choosing whether the ``__name__``
attribute of the decorated/wrapped function should be changed or kept.
Defaults to False (i.e., changes the name by default).
Returns
-------
A decorator/wrapper function to be used once on the new strategy to be
added.
Example
-------
Let's create a StrategyDict that knows its name:
>>> txt_proc = StrategyDict("txt_proc")
Add a first strategy ``swapcase``, using this method as a decorator
factory:
>>> @txt_proc.strategy("swapcase")
... def txt_proc(txt):
... return txt.swapcase()
Let's do it again, but wrapping the strategy functions inline. First two
strategies have multiple names, the last keeps the function name, which
would otherwise be replaced by the first given name:
>>> txt_proc.strategy("lower", "low")(lambda txt: txt.lower())
{(...): <function ... at 0x...>, (...): <function ... at 0x...>}
>>> txt_proc.strategy("upper", "up")(lambda txt: txt.upper())
{...}
>>> txt_proc.strategy("keep", keep_name=True)(lambda txt: txt)
{...}
We can now iterate through the strategies to call them or see their
function names
>>> sorted(st("Just a Test") for st in txt_proc)
['JUST A TEST', 'Just a Test', 'jUST A tEST', 'just a test']
>>> sorted(st.__name__ for st in txt_proc) # Just the first name
['<lambda>', 'lower', 'swapcase', 'upper']
Calling a single strategy:
>>> txt_proc.low("TeStInG")
'testing'
>>> txt_proc["upper"]("TeStInG")
'TESTING'
>>> txt_proc("TeStInG") # Default is the first: swapcase
'tEsTiNg'
>>> txt_proc.default("TeStInG")
'tEsTiNg'
>>> txt_proc.default = txt_proc.up # Manually changing the default
>>> txt_proc("TeStInG")
'TESTING'
Hint
----
Default strategy is the one stored as the ``default`` attribute, you can
change or remove it at any time. When removing all keys that are assigned
to the default strategy, the default attribute will be removed from the
StrategyDict instance as well. The first strategy added afterwards is the
one that will become the new default, unless the attribute is created or
changed manually.
"""
def decorator(func):
keep_name = kwargs.pop("keep_name", False)
if kwargs:
key = next(iter(kwargs))
raise TypeError("Unknown keyword argument '{}'".format(key))
if not keep_name:
func.__name__ = str(names[0])
self[names] = func
return self
return decorator |
0, module; 1, function_definition; 2, function_name:humansort; 3, parameters; 4, block; 5, identifier:l; 6, expression_statement; 7, import_statement; 8, function_definition; 9, expression_statement; 10, return_statement; 11, comment:"""Sort in place a given list the way humans expect.
E.g. ['file11', 'file1'] -> ['file1', 'file11']
"""; 12, dotted_name; 13, function_name:alphanum_key; 14, parameters; 15, comment:# Turn a string into a list of string and number chunks.; 16, comment:# e.g. "z23a" -> ["z", 23, "a"]; 17, block; 18, call; 19, None; 20, identifier:re; 21, identifier:s; 22, function_definition; 23, return_statement; 24, attribute; 25, argument_list; 26, function_name:tryint; 27, parameters; 28, block; 29, list_comprehension; 30, identifier:l; 31, identifier:sort; 32, keyword_argument; 33, identifier:s; 34, if_statement; 35, return_statement; 36, call; 37, for_in_clause; 38, identifier:key; 39, identifier:alphanum_key; 40, call; 41, block; 42, identifier:s; 43, identifier:tryint; 44, argument_list; 45, identifier:c; 46, call; 47, attribute; 48, argument_list; 49, return_statement; 50, identifier:c; 51, attribute; 52, argument_list; 53, identifier:s; 54, identifier:isdigit; 55, call; 56, identifier:re; 57, identifier:split; 58, string:"([0-9]+)"; 59, identifier:s; 60, identifier:int; 61, argument_list; 62, identifier:s | 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; 8, 16; 8, 17; 9, 18; 10, 19; 12, 20; 14, 21; 17, 22; 17, 23; 18, 24; 18, 25; 22, 26; 22, 27; 22, 28; 23, 29; 24, 30; 24, 31; 25, 32; 27, 33; 28, 34; 28, 35; 29, 36; 29, 37; 32, 38; 32, 39; 34, 40; 34, 41; 35, 42; 36, 43; 36, 44; 37, 45; 37, 46; 40, 47; 40, 48; 41, 49; 44, 50; 46, 51; 46, 52; 47, 53; 47, 54; 49, 55; 51, 56; 51, 57; 52, 58; 52, 59; 55, 60; 55, 61; 61, 62 | def humansort(l):
"""Sort in place a given list the way humans expect.
E.g. ['file11', 'file1'] -> ['file1', 'file11']
"""
import re
def alphanum_key(s):
# Turn a string into a list of string and number chunks.
# e.g. "z23a" -> ["z", 23, "a"]
def tryint(s):
if s.isdigit():
return int(s)
return s
return [tryint(c) for c in re.split("([0-9]+)", s)]
l.sort(key=alphanum_key)
return None |
0, module; 1, function_definition; 2, function_name:add; 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, list_splat_pattern; 13, dictionary_splat_pattern; 14, expression_statement; 15, expression_statement; 16, comment:# noqa E126; 17, if_statement; 18, return_statement; 19, identifier:name; 20, string; 21, identifier:type; 22, string; 23, identifier:agent; 24, string; 25, identifier:scanner; 26, string; 27, identifier:location; 28, string; 29, identifier:language; 30, string; 31, identifier:args; 32, identifier:kwargs; 33, comment:""" Simplified add for the most common options.
Parameters:
name (str): Name of the library
agent (str): Example com.plexapp.agents.imdb
type (str): movie, show, # check me
location (str): /path/to/files
language (str): Two letter language fx en
kwargs (dict): Advanced options should be passed as a dict. where the id is the key.
**Photo Preferences**
* **agent** (str): com.plexapp.agents.none
* **enableAutoPhotoTags** (bool): Tag photos. Default value false.
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Photo Scanner
**Movie Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Movie Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source, Default value 0 Possible options:
0:Rotten Tomatoes, 1:IMDb, 2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Default value 46 Possible options 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador,
16:France, 17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland,
22:Italy, 23:Jamaica, 24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands,
29:New Zealand, 30:Nicaragua, 31:Panama, 32:Paraguay, 33:Peru, 34:Portugal,
35:Peoples Republic of China, 36:Puerto Rico, 37:Russia, 38:Singapore, 39:South Africa,
40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad, 45:United Kingdom,
46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Movie Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 Possible
options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada,
9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain,
42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay,
49:Venezuela.
**Show Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.thetvdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **episodeSort** (int): Episode order. Default -1 Possible options: 0:Oldest first, 1:Newest first.
* **flattenSeasons** (int): Seasons. Default value 0 Possible options: 0:Show,1:Hide.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Series Scanner
**TheTVDB Show Options** (com.plexapp.agents.thetvdb)
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
**TheMovieDB Show Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 options
0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile,
10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa,
41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States,
48:Uruguay, 49:Venezuela.
**Other Video Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Other Video Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source Default value 0 Possible options:
0:Rotten Tomatoes,1:IMDb,2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Country: Default value 46 Possible options: 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador, 16:France,
17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland, 22:Italy, 23:Jamaica,
24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands, 29:New Zealand, 30:Nicaragua,
31:Panama, 32:Paraguay, 33:Peru, 34:Portugal, 35:Peoples Republic of China, 36:Puerto Rico,
37:Russia, 38:Singapore, 39:South Africa, 40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad,
45:United Kingdom, 46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Other Video Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default
value 47 Possible options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize,
6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic,
13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany,
19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica,
25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand,
31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore,
40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad,
46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela.
"""; 34, assignment; 35, identifier:kwargs; 36, block; 37, call; 38, string_content:en; 39, identifier:part; 40, binary_operator:'/library/sections?name=%s&type=%s&agent=%s&scanner=%s&language=%s&location=%s' % (
quote_plus(name), type, agent, quote_plus(scanner), language, quote_plus(location)); 41, expression_statement; 42, attribute; 43, argument_list; 44, string; 45, tuple; 46, augmented_assignment; 47, attribute; 48, identifier:query; 49, identifier:part; 50, keyword_argument; 51, string_content:/library/sections?name=%s&type=%s&agent=%s&scanner=%s&language=%s&location=%s; 52, call; 53, identifier:type; 54, identifier:agent; 55, call; 56, identifier:language; 57, call; 58, identifier:part; 59, call; 60, identifier:self; 61, identifier:_server; 62, identifier:method; 63, attribute; 64, identifier:quote_plus; 65, argument_list; 66, identifier:quote_plus; 67, argument_list; 68, identifier:quote_plus; 69, argument_list; 70, identifier:urlencode; 71, argument_list; 72, attribute; 73, identifier:post; 74, identifier:name; 75, identifier:scanner; 76, identifier:location; 77, identifier:kwargs; 78, attribute; 79, identifier:_session; 80, identifier:self; 81, identifier:_server | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 4, 14; 4, 15; 4, 16; 4, 17; 4, 18; 6, 19; 6, 20; 7, 21; 7, 22; 8, 23; 8, 24; 9, 25; 9, 26; 10, 27; 10, 28; 11, 29; 11, 30; 12, 31; 13, 32; 14, 33; 15, 34; 17, 35; 17, 36; 18, 37; 30, 38; 34, 39; 34, 40; 36, 41; 37, 42; 37, 43; 40, 44; 40, 45; 41, 46; 42, 47; 42, 48; 43, 49; 43, 50; 44, 51; 45, 52; 45, 53; 45, 54; 45, 55; 45, 56; 45, 57; 46, 58; 46, 59; 47, 60; 47, 61; 50, 62; 50, 63; 52, 64; 52, 65; 55, 66; 55, 67; 57, 68; 57, 69; 59, 70; 59, 71; 63, 72; 63, 73; 65, 74; 67, 75; 69, 76; 71, 77; 72, 78; 72, 79; 78, 80; 78, 81 | def add(self, name='', type='', agent='', scanner='', location='', language='en', *args, **kwargs):
""" Simplified add for the most common options.
Parameters:
name (str): Name of the library
agent (str): Example com.plexapp.agents.imdb
type (str): movie, show, # check me
location (str): /path/to/files
language (str): Two letter language fx en
kwargs (dict): Advanced options should be passed as a dict. where the id is the key.
**Photo Preferences**
* **agent** (str): com.plexapp.agents.none
* **enableAutoPhotoTags** (bool): Tag photos. Default value false.
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Photo Scanner
**Movie Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Movie Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source, Default value 0 Possible options:
0:Rotten Tomatoes, 1:IMDb, 2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Default value 46 Possible options 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador,
16:France, 17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland,
22:Italy, 23:Jamaica, 24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands,
29:New Zealand, 30:Nicaragua, 31:Panama, 32:Paraguay, 33:Peru, 34:Portugal,
35:Peoples Republic of China, 36:Puerto Rico, 37:Russia, 38:Singapore, 39:South Africa,
40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad, 45:United Kingdom,
46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Movie Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 Possible
options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada,
9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain,
42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay,
49:Venezuela.
**Show Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.thetvdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **episodeSort** (int): Episode order. Default -1 Possible options: 0:Oldest first, 1:Newest first.
* **flattenSeasons** (int): Seasons. Default value 0 Possible options: 0:Show,1:Hide.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Series Scanner
**TheTVDB Show Options** (com.plexapp.agents.thetvdb)
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
**TheMovieDB Show Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 options
0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile,
10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa,
41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States,
48:Uruguay, 49:Venezuela.
**Other Video Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Other Video Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source Default value 0 Possible options:
0:Rotten Tomatoes,1:IMDb,2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Country: Default value 46 Possible options: 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador, 16:France,
17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland, 22:Italy, 23:Jamaica,
24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands, 29:New Zealand, 30:Nicaragua,
31:Panama, 32:Paraguay, 33:Peru, 34:Portugal, 35:Peoples Republic of China, 36:Puerto Rico,
37:Russia, 38:Singapore, 39:South Africa, 40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad,
45:United Kingdom, 46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Other Video Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default
value 47 Possible options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize,
6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic,
13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany,
19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica,
25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand,
31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore,
40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad,
46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela.
"""
part = '/library/sections?name=%s&type=%s&agent=%s&scanner=%s&language=%s&location=%s' % (
quote_plus(name), type, agent, quote_plus(scanner), language, quote_plus(location)) # noqa E126
if kwargs:
part += urlencode(kwargs)
return self._server.query(part, method=self._server._session.post) |
0, module; 1, function_definition; 2, function_name:all; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, dictionary_splat_pattern; 8, expression_statement; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, return_statement; 13, identifier:sort; 14, None; 15, identifier:kwargs; 16, comment:""" Returns a list of media from this library section.
Parameters:
sort (string): The sort string
"""; 17, assignment; 18, comparison_operator:sort is not None; 19, block; 20, assignment; 21, call; 22, identifier:sortStr; 23, string; 24, identifier:sort; 25, None; 26, expression_statement; 27, identifier:key; 28, binary_operator:'/library/sections/%s/all%s' % (self.key, sortStr); 29, attribute; 30, argument_list; 31, assignment; 32, string; 33, tuple; 34, identifier:self; 35, identifier:fetchItems; 36, identifier:key; 37, dictionary_splat; 38, identifier:sortStr; 39, binary_operator:'?sort=' + sort; 40, string_content:/library/sections/%s/all%s; 41, attribute; 42, identifier:sortStr; 43, identifier:kwargs; 44, string; 45, identifier:sort; 46, identifier:self; 47, identifier:key; 48, string_content:?sort= | 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; 8, 16; 9, 17; 10, 18; 10, 19; 11, 20; 12, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 20, 27; 20, 28; 21, 29; 21, 30; 26, 31; 28, 32; 28, 33; 29, 34; 29, 35; 30, 36; 30, 37; 31, 38; 31, 39; 32, 40; 33, 41; 33, 42; 37, 43; 39, 44; 39, 45; 41, 46; 41, 47; 44, 48 | def all(self, sort=None, **kwargs):
""" Returns a list of media from this library section.
Parameters:
sort (string): The sort string
"""
sortStr = ''
if sort is not None:
sortStr = '?sort=' + sort
key = '/library/sections/%s/all%s' % (self.key, sortStr)
return self.fetchItems(key, **kwargs) |
0, module; 1, function_definition; 2, function_name:as_sorted_list; 3, parameters; 4, block; 5, identifier:options; 6, expression_statement; 7, if_statement; 8, return_statement; 9, comment:"""
Returns all options in a list sorted according to their option numbers.
:return: the sorted list
"""; 10, comparison_operator:len(options) > 0; 11, block; 12, identifier:options; 13, call; 14, integer:0; 15, expression_statement; 16, identifier:len; 17, argument_list; 18, assignment; 19, identifier:options; 20, identifier:options; 21, call; 22, identifier:sorted; 23, argument_list; 24, identifier:options; 25, keyword_argument; 26, identifier:key; 27, lambda; 28, lambda_parameters; 29, attribute; 30, identifier:o; 31, identifier:o; 32, identifier:number | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 6, 9; 7, 10; 7, 11; 8, 12; 10, 13; 10, 14; 11, 15; 13, 16; 13, 17; 15, 18; 17, 19; 18, 20; 18, 21; 21, 22; 21, 23; 23, 24; 23, 25; 25, 26; 25, 27; 27, 28; 27, 29; 28, 30; 29, 31; 29, 32 | def as_sorted_list(options):
"""
Returns all options in a list sorted according to their option numbers.
:return: the sorted list
"""
if len(options) > 0:
options = sorted(options, key=lambda o: o.number)
return options |
0, module; 1, function_definition; 2, function_name:df_all; 3, parameters; 4, block; 5, identifier:self; 6, identifier:phot; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, comment:"""Subclasses may want to sort this
"""; 11, assignment; 12, identifier:df; 13, identifier:df; 14, call; 15, attribute; 16, argument_list; 17, identifier:pd; 18, identifier:concat; 19, list_comprehension; 20, call; 21, for_in_clause; 22, attribute; 23, argument_list; 24, identifier:f; 25, call; 26, identifier:self; 27, identifier:to_df; 28, identifier:f; 29, attribute; 30, argument_list; 31, identifier:self; 32, identifier:get_filenames; 33, identifier:phot | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 7, 10; 8, 11; 9, 12; 11, 13; 11, 14; 14, 15; 14, 16; 15, 17; 15, 18; 16, 19; 19, 20; 19, 21; 20, 22; 20, 23; 21, 24; 21, 25; 22, 26; 22, 27; 23, 28; 25, 29; 25, 30; 29, 31; 29, 32; 30, 33 | def df_all(self, phot):
"""Subclasses may want to sort this
"""
df = pd.concat([self.to_df(f) for f in self.get_filenames(phot)])
return df |
0, module; 1, function_definition; 2, function_name:searchsorted; 3, parameters; 4, block; 5, identifier:arr; 6, identifier:N; 7, identifier:x; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, while_statement; 14, return_statement; 15, comment:"""N is length of arr
"""; 16, assignment; 17, assignment; 18, assignment; 19, assignment; 20, not_operator; 21, block; 22, identifier:L; 23, identifier:L; 24, integer:0; 25, identifier:R; 26, binary_operator:N-1; 27, identifier:done; 28, False; 29, identifier:m; 30, binary_operator:(L+R)//2; 31, identifier:done; 32, if_statement; 33, expression_statement; 34, if_statement; 35, identifier:N; 36, integer:1; 37, parenthesized_expression; 38, integer:2; 39, comparison_operator:arr[m] < x; 40, block; 41, elif_clause; 42, elif_clause; 43, assignment; 44, comparison_operator:L>R; 45, block; 46, binary_operator:L+R; 47, subscript; 48, identifier:x; 49, expression_statement; 50, comparison_operator:arr[m] > x; 51, block; 52, comparison_operator:arr[m] == x; 53, block; 54, identifier:m; 55, binary_operator:(L+R)//2; 56, identifier:L; 57, identifier:R; 58, expression_statement; 59, identifier:L; 60, identifier:R; 61, identifier:arr; 62, identifier:m; 63, assignment; 64, subscript; 65, identifier:x; 66, expression_statement; 67, subscript; 68, identifier:x; 69, expression_statement; 70, parenthesized_expression; 71, integer:2; 72, assignment; 73, identifier:L; 74, binary_operator:m + 1; 75, identifier:arr; 76, identifier:m; 77, assignment; 78, identifier:arr; 79, identifier:m; 80, assignment; 81, binary_operator:L+R; 82, identifier:done; 83, True; 84, identifier:m; 85, integer:1; 86, identifier:R; 87, binary_operator:m - 1; 88, identifier:done; 89, True; 90, identifier:L; 91, identifier:R; 92, identifier:m; 93, integer:1 | 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; 8, 15; 9, 16; 10, 17; 11, 18; 12, 19; 13, 20; 13, 21; 14, 22; 16, 23; 16, 24; 17, 25; 17, 26; 18, 27; 18, 28; 19, 29; 19, 30; 20, 31; 21, 32; 21, 33; 21, 34; 26, 35; 26, 36; 30, 37; 30, 38; 32, 39; 32, 40; 32, 41; 32, 42; 33, 43; 34, 44; 34, 45; 37, 46; 39, 47; 39, 48; 40, 49; 41, 50; 41, 51; 42, 52; 42, 53; 43, 54; 43, 55; 44, 56; 44, 57; 45, 58; 46, 59; 46, 60; 47, 61; 47, 62; 49, 63; 50, 64; 50, 65; 51, 66; 52, 67; 52, 68; 53, 69; 55, 70; 55, 71; 58, 72; 63, 73; 63, 74; 64, 75; 64, 76; 66, 77; 67, 78; 67, 79; 69, 80; 70, 81; 72, 82; 72, 83; 74, 84; 74, 85; 77, 86; 77, 87; 80, 88; 80, 89; 81, 90; 81, 91; 87, 92; 87, 93 | def searchsorted(arr, N, x):
"""N is length of arr
"""
L = 0
R = N-1
done = False
m = (L+R)//2
while not done:
if arr[m] < x:
L = m + 1
elif arr[m] > x:
R = m - 1
elif arr[m] == x:
done = True
m = (L+R)//2
if L>R:
done = True
return L |
0, module; 1, function_definition; 2, function_name:_plot_spectrogram; 3, parameters; 4, block; 5, identifier:G; 6, identifier:node_idx; 7, expression_statement; 8, import_from_statement; 9, expression_statement; 10, if_statement; 11, expression_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, expression_statement; 22, expression_statement; 23, expression_statement; 24, expression_statement; 25, expression_statement; 26, expression_statement; 27, global_statement; 28, expression_statement; 29, comment:r"""Plot the graph's spectrogram.
Parameters
----------
node_idx : ndarray
Order to sort the nodes in the spectrogram.
By default, does not reorder the nodes.
Notes
-----
This function is only implemented for the pyqtgraph backend at the moment.
Examples
--------
>>> G = graphs.Ring(15)
>>> G.plot_spectrogram()
"""; 30, dotted_name; 31, dotted_name; 32, assignment; 33, not_operator; 34, block; 35, assignment; 36, assignment; 37, assignment; 38, assignment; 39, assignment; 40, assignment; 41, assignment; 42, assignment; 43, assignment; 44, assignment; 45, call; 46, assignment; 47, assignment; 48, call; 49, assignment; 50, call; 51, identifier:_qtg_windows; 52, call; 53, identifier:pygsp; 54, identifier:features; 55, pattern_list; 56, call; 57, call; 58, expression_statement; 59, identifier:M; 60, subscript; 61, identifier:spectr; 62, conditional_expression:G.spectr[node_idx, :] if node_idx is not None else G.spectr; 63, identifier:spectr; 64, call; 65, pattern_list; 66, expression_list; 67, identifier:pos; 68, call; 69, identifier:color; 70, list; 71, identifier:color; 72, call; 73, identifier:cmap; 74, call; 75, identifier:spectr; 76, binary_operator:(spectr.astype(float) - min_spec) / (max_spec - min_spec); 77, identifier:w; 78, call; 79, attribute; 80, argument_list; 81, identifier:label; 82, call; 83, identifier:v; 84, call; 85, attribute; 86, argument_list; 87, identifier:spi; 88, call; 89, attribute; 90, argument_list; 91, attribute; 92, argument_list; 93, identifier:qtg; 94, identifier:_; 95, identifier:_; 96, identifier:_import_qtg; 97, argument_list; 98, identifier:hasattr; 99, argument_list; 100, call; 101, attribute; 102, integer:1; 103, subscript; 104, comparison_operator:node_idx is not None; 105, attribute; 106, attribute; 107, argument_list; 108, identifier:min_spec; 109, identifier:max_spec; 110, call; 111, call; 112, attribute; 113, argument_list; 114, list; 115, list; 116, list; 117, list; 118, list; 119, attribute; 120, argument_list; 121, attribute; 122, argument_list; 123, parenthesized_expression; 124, parenthesized_expression; 125, attribute; 126, argument_list; 127, identifier:w; 128, identifier:setWindowTitle; 129, call; 130, attribute; 131, argument_list; 132, attribute; 133, argument_list; 134, identifier:v; 135, identifier:setAspectLocked; 136, attribute; 137, argument_list; 138, identifier:v; 139, identifier:addItem; 140, identifier:spi; 141, identifier:_qtg_windows; 142, identifier:append; 143, identifier:w; 144, identifier:G; 145, string; 146, attribute; 147, argument_list; 148, attribute; 149, identifier:shape; 150, attribute; 151, identifier:node_idx; 152, slice; 153, identifier:node_idx; 154, None; 155, identifier:G; 156, identifier:spectr; 157, identifier:np; 158, identifier:ravel; 159, identifier:spectr; 160, attribute; 161, argument_list; 162, attribute; 163, argument_list; 164, identifier:np; 165, identifier:array; 166, list; 167, integer:20; 168, integer:133; 169, integer:212; 170, integer:255; 171, integer:53; 172, integer:42; 173, integer:135; 174, integer:255; 175, integer:48; 176, integer:174; 177, integer:170; 178, integer:255; 179, integer:210; 180, integer:184; 181, integer:87; 182, integer:255; 183, integer:249; 184, integer:251; 185, integer:14; 186, integer:255; 187, identifier:np; 188, identifier:array; 189, identifier:color; 190, keyword_argument; 191, identifier:qtg; 192, identifier:ColorMap; 193, identifier:pos; 194, identifier:color; 195, binary_operator:spectr.astype(float) - min_spec; 196, binary_operator:max_spec - min_spec; 197, identifier:qtg; 198, identifier:GraphicsWindow; 199, attribute; 200, argument_list; 201, string; 202, identifier:format; 203, integer:0; 204, binary_operator:G.lmax/M; 205, attribute; 206, identifier:w; 207, identifier:addPlot; 208, keyword_argument; 209, identifier:qtg; 210, identifier:ScatterPlotItem; 211, call; 212, call; 213, keyword_argument; 214, keyword_argument; 215, keyword_argument; 216, keyword_argument; 217, string_content:spectr; 218, identifier:features; 219, identifier:compute_spectrogram; 220, identifier:G; 221, identifier:G; 222, identifier:spectr; 223, identifier:G; 224, identifier:spectr; 225, identifier:spectr; 226, identifier:min; 227, identifier:spectr; 228, identifier:max; 229, float:0.; 230, float:0.25; 231, float:0.5; 232, float:0.75; 233, float:1.; 234, identifier:dtype; 235, attribute; 236, call; 237, identifier:min_spec; 238, identifier:max_spec; 239, identifier:min_spec; 240, string:"Spectrogram of {}"; 241, identifier:format; 242, call; 243, string_content:frequencies {}:{:.2f}:{:.2f}; 244, attribute; 245, identifier:M; 246, identifier:G; 247, identifier:lmax; 248, identifier:labels; 249, dictionary; 250, attribute; 251, argument_list; 252, attribute; 253, argument_list; 254, identifier:pxMode; 255, False; 256, identifier:symbol; 257, string; 258, identifier:size; 259, integer:1; 260, identifier:brush; 261, call; 262, identifier:np; 263, identifier:ubyte; 264, attribute; 265, argument_list; 266, attribute; 267, argument_list; 268, identifier:G; 269, identifier:lmax; 270, pair; 271, pair; 272, identifier:np; 273, identifier:repeat; 274, call; 275, identifier:M; 276, identifier:np; 277, identifier:ravel; 278, call; 279, string_content:s; 280, attribute; 281, argument_list; 282, identifier:spectr; 283, identifier:astype; 284, identifier:float; 285, identifier:G; 286, identifier:__repr__; 287, keyword_argument; 288, string; 289, string; 290, string; 291, identifier:label; 292, attribute; 293, argument_list; 294, attribute; 295, argument_list; 296, identifier:cmap; 297, identifier:map; 298, identifier:spectr; 299, string; 300, identifier:limit; 301, integer:4; 302, string_content:bottom; 303, string_content:nodes; 304, string_content:left; 305, identifier:np; 306, identifier:arange; 307, attribute; 308, identifier:np; 309, identifier:tile; 310, call; 311, tuple; 312, string_content:qcolor; 313, identifier:G; 314, identifier:N; 315, attribute; 316, argument_list; 317, integer:1; 318, attribute; 319, identifier:np; 320, identifier:arange; 321, identifier:M; 322, identifier:G; 323, 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; 7, 29; 8, 30; 8, 31; 9, 32; 10, 33; 10, 34; 11, 35; 12, 36; 13, 37; 14, 38; 15, 39; 16, 40; 17, 41; 18, 42; 19, 43; 20, 44; 21, 45; 22, 46; 23, 47; 24, 48; 25, 49; 26, 50; 27, 51; 28, 52; 30, 53; 31, 54; 32, 55; 32, 56; 33, 57; 34, 58; 35, 59; 35, 60; 36, 61; 36, 62; 37, 63; 37, 64; 38, 65; 38, 66; 39, 67; 39, 68; 40, 69; 40, 70; 41, 71; 41, 72; 42, 73; 42, 74; 43, 75; 43, 76; 44, 77; 44, 78; 45, 79; 45, 80; 46, 81; 46, 82; 47, 83; 47, 84; 48, 85; 48, 86; 49, 87; 49, 88; 50, 89; 50, 90; 52, 91; 52, 92; 55, 93; 55, 94; 55, 95; 56, 96; 56, 97; 57, 98; 57, 99; 58, 100; 60, 101; 60, 102; 62, 103; 62, 104; 62, 105; 64, 106; 64, 107; 65, 108; 65, 109; 66, 110; 66, 111; 68, 112; 68, 113; 70, 114; 70, 115; 70, 116; 70, 117; 70, 118; 72, 119; 72, 120; 74, 121; 74, 122; 76, 123; 76, 124; 78, 125; 78, 126; 79, 127; 79, 128; 80, 129; 82, 130; 82, 131; 84, 132; 84, 133; 85, 134; 85, 135; 88, 136; 88, 137; 89, 138; 89, 139; 90, 140; 91, 141; 91, 142; 92, 143; 99, 144; 99, 145; 100, 146; 100, 147; 101, 148; 101, 149; 103, 150; 103, 151; 103, 152; 104, 153; 104, 154; 105, 155; 105, 156; 106, 157; 106, 158; 107, 159; 110, 160; 110, 161; 111, 162; 111, 163; 112, 164; 112, 165; 113, 166; 114, 167; 114, 168; 114, 169; 114, 170; 115, 171; 115, 172; 115, 173; 115, 174; 116, 175; 116, 176; 116, 177; 116, 178; 117, 179; 117, 180; 117, 181; 117, 182; 118, 183; 118, 184; 118, 185; 118, 186; 119, 187; 119, 188; 120, 189; 120, 190; 121, 191; 121, 192; 122, 193; 122, 194; 123, 195; 124, 196; 125, 197; 125, 198; 129, 199; 129, 200; 130, 201; 130, 202; 131, 203; 131, 204; 131, 205; 132, 206; 132, 207; 133, 208; 136, 209; 136, 210; 137, 211; 137, 212; 137, 213; 137, 214; 137, 215; 137, 216; 145, 217; 146, 218; 146, 219; 147, 220; 148, 221; 148, 222; 150, 223; 150, 224; 160, 225; 160, 226; 162, 227; 162, 228; 166, 229; 166, 230; 166, 231; 166, 232; 166, 233; 190, 234; 190, 235; 195, 236; 195, 237; 196, 238; 196, 239; 199, 240; 199, 241; 200, 242; 201, 243; 204, 244; 204, 245; 205, 246; 205, 247; 208, 248; 208, 249; 211, 250; 211, 251; 212, 252; 212, 253; 213, 254; 213, 255; 214, 256; 214, 257; 215, 258; 215, 259; 216, 260; 216, 261; 235, 262; 235, 263; 236, 264; 236, 265; 242, 266; 242, 267; 244, 268; 244, 269; 249, 270; 249, 271; 250, 272; 250, 273; 251, 274; 251, 275; 252, 276; 252, 277; 253, 278; 257, 279; 261, 280; 261, 281; 264, 282; 264, 283; 265, 284; 266, 285; 266, 286; 267, 287; 270, 288; 270, 289; 271, 290; 271, 291; 274, 292; 274, 293; 278, 294; 278, 295; 280, 296; 280, 297; 281, 298; 281, 299; 287, 300; 287, 301; 288, 302; 289, 303; 290, 304; 292, 305; 292, 306; 293, 307; 294, 308; 294, 309; 295, 310; 295, 311; 299, 312; 307, 313; 307, 314; 310, 315; 310, 316; 311, 317; 311, 318; 315, 319; 315, 320; 316, 321; 318, 322; 318, 323 | def _plot_spectrogram(G, node_idx):
r"""Plot the graph's spectrogram.
Parameters
----------
node_idx : ndarray
Order to sort the nodes in the spectrogram.
By default, does not reorder the nodes.
Notes
-----
This function is only implemented for the pyqtgraph backend at the moment.
Examples
--------
>>> G = graphs.Ring(15)
>>> G.plot_spectrogram()
"""
from pygsp import features
qtg, _, _ = _import_qtg()
if not hasattr(G, 'spectr'):
features.compute_spectrogram(G)
M = G.spectr.shape[1]
spectr = G.spectr[node_idx, :] if node_idx is not None else G.spectr
spectr = np.ravel(spectr)
min_spec, max_spec = spectr.min(), spectr.max()
pos = np.array([0., 0.25, 0.5, 0.75, 1.])
color = [[20, 133, 212, 255], [53, 42, 135, 255], [48, 174, 170, 255],
[210, 184, 87, 255], [249, 251, 14, 255]]
color = np.array(color, dtype=np.ubyte)
cmap = qtg.ColorMap(pos, color)
spectr = (spectr.astype(float) - min_spec) / (max_spec - min_spec)
w = qtg.GraphicsWindow()
w.setWindowTitle("Spectrogram of {}".format(G.__repr__(limit=4)))
label = 'frequencies {}:{:.2f}:{:.2f}'.format(0, G.lmax/M, G.lmax)
v = w.addPlot(labels={'bottom': 'nodes',
'left': label})
v.setAspectLocked()
spi = qtg.ScatterPlotItem(np.repeat(np.arange(G.N), M),
np.ravel(np.tile(np.arange(M), (1, G.N))),
pxMode=False,
symbol='s',
size=1,
brush=cmap.map(spectr, 'qcolor'))
v.addItem(spi)
global _qtg_windows
_qtg_windows.append(w) |
0, module; 1, function_definition; 2, function_name:write_omega_scan_config; 3, parameters; 4, block; 5, identifier:channellist; 6, identifier:fobj; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, try_statement; 11, identifier:header; 12, True; 13, comment:"""Write a `ChannelList` to an Omega-pipeline scan configuration file
This method is dumb and assumes the channels are sorted in the right
order already
"""; 14, call; 15, block; 16, else_clause; 17, comment:# print header; 18, block; 19, finally_clause; 20, identifier:isinstance; 21, argument_list; 22, expression_statement; 23, block; 24, if_statement; 25, expression_statement; 26, for_statement; 27, block; 28, identifier:fobj; 29, identifier:FILE_LIKE; 30, assignment; 31, expression_statement; 32, expression_statement; 33, identifier:header; 34, block; 35, assignment; 36, identifier:channel; 37, identifier:channellist; 38, comment:# print header; 39, block; 40, if_statement; 41, identifier:close; 42, False; 43, assignment; 44, assignment; 45, expression_statement; 46, expression_statement; 47, identifier:group; 48, None; 49, if_statement; 50, expression_statement; 51, expression_statement; 52, identifier:close; 53, block; 54, identifier:fobj; 55, call; 56, identifier:close; 57, True; 58, call; 59, call; 60, comparison_operator:channel.group != group; 61, block; 62, call; 63, call; 64, expression_statement; 65, identifier:open; 66, argument_list; 67, identifier:print; 68, argument_list; 69, identifier:print; 70, argument_list; 71, attribute; 72, identifier:group; 73, expression_statement; 74, expression_statement; 75, identifier:print; 76, argument_list; 77, identifier:print_omega_channel; 78, argument_list; 79, call; 80, identifier:fobj; 81, string; 82, string; 83, keyword_argument; 84, string; 85, keyword_argument; 86, identifier:channel; 87, identifier:group; 88, assignment; 89, call; 90, string:""; 91, keyword_argument; 92, identifier:channel; 93, keyword_argument; 94, attribute; 95, argument_list; 96, string_content:w; 97, string_content:# Q Scan configuration file; 98, identifier:file; 99, identifier:fobj; 100, string_content:# Generated with GWpy from a ChannelList; 101, identifier:file; 102, identifier:fobj; 103, identifier:group; 104, attribute; 105, identifier:print; 106, argument_list; 107, identifier:file; 108, identifier:fobj; 109, identifier:file; 110, identifier:fobj; 111, identifier:fobj; 112, identifier:close; 113, identifier:channel; 114, identifier:group; 115, binary_operator:'\n[%s]' % group; 116, keyword_argument; 117, string; 118, identifier:group; 119, identifier:file; 120, identifier:fobj; 121, string_content; 122, escape_sequence:\n | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 7, 11; 7, 12; 8, 13; 9, 14; 9, 15; 9, 16; 10, 17; 10, 18; 10, 19; 14, 20; 14, 21; 15, 22; 16, 23; 18, 24; 18, 25; 18, 26; 19, 27; 21, 28; 21, 29; 22, 30; 23, 31; 23, 32; 24, 33; 24, 34; 25, 35; 26, 36; 26, 37; 26, 38; 26, 39; 27, 40; 30, 41; 30, 42; 31, 43; 32, 44; 34, 45; 34, 46; 35, 47; 35, 48; 39, 49; 39, 50; 39, 51; 40, 52; 40, 53; 43, 54; 43, 55; 44, 56; 44, 57; 45, 58; 46, 59; 49, 60; 49, 61; 50, 62; 51, 63; 53, 64; 55, 65; 55, 66; 58, 67; 58, 68; 59, 69; 59, 70; 60, 71; 60, 72; 61, 73; 61, 74; 62, 75; 62, 76; 63, 77; 63, 78; 64, 79; 66, 80; 66, 81; 68, 82; 68, 83; 70, 84; 70, 85; 71, 86; 71, 87; 73, 88; 74, 89; 76, 90; 76, 91; 78, 92; 78, 93; 79, 94; 79, 95; 81, 96; 82, 97; 83, 98; 83, 99; 84, 100; 85, 101; 85, 102; 88, 103; 88, 104; 89, 105; 89, 106; 91, 107; 91, 108; 93, 109; 93, 110; 94, 111; 94, 112; 104, 113; 104, 114; 106, 115; 106, 116; 115, 117; 115, 118; 116, 119; 116, 120; 117, 121; 121, 122 | def write_omega_scan_config(channellist, fobj, header=True):
"""Write a `ChannelList` to an Omega-pipeline scan configuration file
This method is dumb and assumes the channels are sorted in the right
order already
"""
if isinstance(fobj, FILE_LIKE):
close = False
else:
fobj = open(fobj, 'w')
close = True
try:
# print header
if header:
print('# Q Scan configuration file', file=fobj)
print('# Generated with GWpy from a ChannelList', file=fobj)
group = None
for channel in channellist:
# print header
if channel.group != group:
group = channel.group
print('\n[%s]' % group, file=fobj)
print("", file=fobj)
print_omega_channel(channel, file=fobj)
finally:
if close:
fobj.close() |
0, module; 1, function_definition; 2, function_name:coalesce; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, while_statement; 11, delete_statement; 12, return_statement; 13, comment:"""Merge contiguous elements of this list into single objects
This method implicitly sorts and potentially shortens this list.
"""; 14, call; 15, assignment; 16, assignment; 17, comparison_operator:j < N; 18, block; 19, subscript; 20, identifier:self; 21, attribute; 22, argument_list; 23, identifier:i; 24, assignment; 25, identifier:N; 26, call; 27, identifier:j; 28, identifier:N; 29, expression_statement; 30, expression_statement; 31, if_statement; 32, expression_statement; 33, identifier:self; 34, slice; 35, identifier:self; 36, identifier:sort; 37, keyword_argument; 38, identifier:j; 39, integer:0; 40, identifier:len; 41, argument_list; 42, assignment; 43, augmented_assignment; 44, boolean_operator; 45, block; 46, else_clause; 47, augmented_assignment; 48, identifier:i; 49, identifier:key; 50, lambda; 51, identifier:self; 52, identifier:this; 53, subscript; 54, identifier:j; 55, integer:1; 56, comparison_operator:j < N; 57, comparison_operator:this.is_contiguous(self[j]) == 1; 58, while_statement; 59, block; 60, identifier:i; 61, integer:1; 62, lambda_parameters; 63, attribute; 64, identifier:self; 65, identifier:j; 66, identifier:j; 67, identifier:N; 68, call; 69, integer:1; 70, boolean_operator; 71, block; 72, expression_statement; 73, identifier:ts; 74, attribute; 75, identifier:value; 76, attribute; 77, argument_list; 78, comparison_operator:j < N; 79, call; 80, try_statement; 81, expression_statement; 82, assignment; 83, identifier:ts; 84, identifier:t0; 85, identifier:this; 86, identifier:is_contiguous; 87, subscript; 88, identifier:j; 89, identifier:N; 90, attribute; 91, argument_list; 92, block; 93, except_clause; 94, augmented_assignment; 95, subscript; 96, identifier:this; 97, identifier:self; 98, identifier:j; 99, identifier:this; 100, identifier:is_contiguous; 101, subscript; 102, expression_statement; 103, as_pattern; 104, block; 105, identifier:j; 106, integer:1; 107, identifier:self; 108, identifier:i; 109, identifier:self; 110, identifier:j; 111, assignment; 112, identifier:ValueError; 113, as_pattern_target; 114, if_statement; 115, identifier:this; 116, assignment; 117, identifier:exc; 118, comparison_operator:'cannot resize this array' in str(exc); 119, block; 120, else_clause; 121, subscript; 122, call; 123, string; 124, call; 125, expression_statement; 126, expression_statement; 127, block; 128, identifier:self; 129, identifier:i; 130, attribute; 131, argument_list; 132, string_content:cannot resize this array; 133, identifier:str; 134, argument_list; 135, assignment; 136, assignment; 137, raise_statement; 138, identifier:this; 139, identifier:append; 140, subscript; 141, identifier:exc; 142, identifier:this; 143, call; 144, identifier:this; 145, assignment; 146, identifier:self; 147, identifier:j; 148, attribute; 149, argument_list; 150, subscript; 151, call; 152, identifier:this; 153, identifier:copy; 154, identifier:self; 155, identifier:i; 156, attribute; 157, argument_list; 158, identifier:this; 159, identifier:append; 160, subscript; 161, identifier:self; 162, identifier:j | 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; 10, 18; 11, 19; 12, 20; 14, 21; 14, 22; 15, 23; 15, 24; 16, 25; 16, 26; 17, 27; 17, 28; 18, 29; 18, 30; 18, 31; 18, 32; 19, 33; 19, 34; 21, 35; 21, 36; 22, 37; 24, 38; 24, 39; 26, 40; 26, 41; 29, 42; 30, 43; 31, 44; 31, 45; 31, 46; 32, 47; 34, 48; 37, 49; 37, 50; 41, 51; 42, 52; 42, 53; 43, 54; 43, 55; 44, 56; 44, 57; 45, 58; 46, 59; 47, 60; 47, 61; 50, 62; 50, 63; 53, 64; 53, 65; 56, 66; 56, 67; 57, 68; 57, 69; 58, 70; 58, 71; 59, 72; 62, 73; 63, 74; 63, 75; 68, 76; 68, 77; 70, 78; 70, 79; 71, 80; 71, 81; 72, 82; 74, 83; 74, 84; 76, 85; 76, 86; 77, 87; 78, 88; 78, 89; 79, 90; 79, 91; 80, 92; 80, 93; 81, 94; 82, 95; 82, 96; 87, 97; 87, 98; 90, 99; 90, 100; 91, 101; 92, 102; 93, 103; 93, 104; 94, 105; 94, 106; 95, 107; 95, 108; 101, 109; 101, 110; 102, 111; 103, 112; 103, 113; 104, 114; 111, 115; 111, 116; 113, 117; 114, 118; 114, 119; 114, 120; 116, 121; 116, 122; 118, 123; 118, 124; 119, 125; 119, 126; 120, 127; 121, 128; 121, 129; 122, 130; 122, 131; 123, 132; 124, 133; 124, 134; 125, 135; 126, 136; 127, 137; 130, 138; 130, 139; 131, 140; 134, 141; 135, 142; 135, 143; 136, 144; 136, 145; 140, 146; 140, 147; 143, 148; 143, 149; 145, 150; 145, 151; 148, 152; 148, 153; 150, 154; 150, 155; 151, 156; 151, 157; 156, 158; 156, 159; 157, 160; 160, 161; 160, 162 | def coalesce(self):
"""Merge contiguous elements of this list into single objects
This method implicitly sorts and potentially shortens this list.
"""
self.sort(key=lambda ts: ts.t0.value)
i = j = 0
N = len(self)
while j < N:
this = self[j]
j += 1
if j < N and this.is_contiguous(self[j]) == 1:
while j < N and this.is_contiguous(self[j]):
try:
this = self[i] = this.append(self[j])
except ValueError as exc:
if 'cannot resize this array' in str(exc):
this = this.copy()
this = self[i] = this.append(self[j])
else:
raise
j += 1
else:
self[i] = this
i += 1
del self[i:]
return self |
0, module; 1, function_definition; 2, function_name:read_cache; 3, parameters; 4, block; 5, identifier:cachefile; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, comment:# open file; 11, if_statement; 12, comment:# read file; 13, expression_statement; 14, comment:# sieve and sort; 15, if_statement; 16, if_statement; 17, comment:# read simple paths; 18, return_statement; 19, identifier:coltype; 20, identifier:LIGOTimeGPS; 21, identifier:sort; 22, None; 23, identifier:segment; 24, None; 25, comment:"""Read a LAL- or FFL-format cache file as a list of file paths
Parameters
----------
cachefile : `str`, `file`
Input file or file path to read.
coltype : `LIGOTimeGPS`, `int`, optional
Type for GPS times.
sort : `callable`, optional
A callable key function by which to sort the output list of file paths
segment : `gwpy.segments.Segment`, optional
A GPS `[start, stop)` interval, if given only files overlapping this
interval will be returned.
Returns
-------
paths : `list` of `str`
A list of file paths as read from the cache file.
"""; 26, not_operator; 27, block; 28, assignment; 29, identifier:segment; 30, block; 31, identifier:sort; 32, block; 33, identifier:cache; 34, call; 35, with_statement; 36, identifier:cache; 37, list_comprehension; 38, expression_statement; 39, expression_statement; 40, identifier:isinstance; 41, argument_list; 42, with_clause; 43, block; 44, attribute; 45, for_in_clause; 46, assignment; 47, call; 48, identifier:cachefile; 49, identifier:FILE_LIKE; 50, with_item; 51, return_statement; 52, identifier:x; 53, identifier:path; 54, identifier:x; 55, call; 56, identifier:cache; 57, call; 58, attribute; 59, argument_list; 60, as_pattern; 61, call; 62, identifier:_iter_cache; 63, argument_list; 64, identifier:sieve; 65, argument_list; 66, identifier:cache; 67, identifier:sort; 68, keyword_argument; 69, call; 70, as_pattern_target; 71, identifier:read_cache; 72, argument_list; 73, identifier:cachefile; 74, keyword_argument; 75, identifier:cache; 76, keyword_argument; 77, identifier:key; 78, identifier:sort; 79, identifier:open; 80, argument_list; 81, identifier:fobj; 82, identifier:fobj; 83, keyword_argument; 84, keyword_argument; 85, keyword_argument; 86, identifier:gpstype; 87, identifier:coltype; 88, identifier:segment; 89, identifier:segment; 90, call; 91, string; 92, identifier:coltype; 93, identifier:coltype; 94, identifier:sort; 95, identifier:sort; 96, identifier:segment; 97, identifier:segment; 98, identifier:file_path; 99, argument_list; 100, string_content:r; 101, identifier:cachefile | 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; 6, 19; 6, 20; 7, 21; 7, 22; 8, 23; 8, 24; 9, 25; 11, 26; 11, 27; 13, 28; 15, 29; 15, 30; 16, 31; 16, 32; 18, 33; 26, 34; 27, 35; 28, 36; 28, 37; 30, 38; 32, 39; 34, 40; 34, 41; 35, 42; 35, 43; 37, 44; 37, 45; 38, 46; 39, 47; 41, 48; 41, 49; 42, 50; 43, 51; 44, 52; 44, 53; 45, 54; 45, 55; 46, 56; 46, 57; 47, 58; 47, 59; 50, 60; 51, 61; 55, 62; 55, 63; 57, 64; 57, 65; 58, 66; 58, 67; 59, 68; 60, 69; 60, 70; 61, 71; 61, 72; 63, 73; 63, 74; 65, 75; 65, 76; 68, 77; 68, 78; 69, 79; 69, 80; 70, 81; 72, 82; 72, 83; 72, 84; 72, 85; 74, 86; 74, 87; 76, 88; 76, 89; 80, 90; 80, 91; 83, 92; 83, 93; 84, 94; 84, 95; 85, 96; 85, 97; 90, 98; 90, 99; 91, 100; 99, 101 | def read_cache(cachefile, coltype=LIGOTimeGPS, sort=None, segment=None):
"""Read a LAL- or FFL-format cache file as a list of file paths
Parameters
----------
cachefile : `str`, `file`
Input file or file path to read.
coltype : `LIGOTimeGPS`, `int`, optional
Type for GPS times.
sort : `callable`, optional
A callable key function by which to sort the output list of file paths
segment : `gwpy.segments.Segment`, optional
A GPS `[start, stop)` interval, if given only files overlapping this
interval will be returned.
Returns
-------
paths : `list` of `str`
A list of file paths as read from the cache file.
"""
# open file
if not isinstance(cachefile, FILE_LIKE):
with open(file_path(cachefile), 'r') as fobj:
return read_cache(fobj, coltype=coltype, sort=sort,
segment=segment)
# read file
cache = [x.path for x in _iter_cache(cachefile, gpstype=coltype)]
# sieve and sort
if segment:
cache = sieve(cache, segment=segment)
if sort:
cache.sort(key=sort)
# read simple paths
return cache |
0, module; 1, function_definition; 2, function_name:get_learned_skills; 3, parameters; 4, block; 5, identifier:self; 6, identifier:lang; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, return_statement; 11, comment:"""
Return the learned skill objects sorted by the order they were learned
in.
"""; 12, assignment; 13, call; 14, list_comprehension; 15, identifier:skills; 16, list_comprehension; 17, attribute; 18, argument_list; 19, identifier:skill; 20, for_in_clause; 21, if_clause; 22, identifier:skill; 23, for_in_clause; 24, identifier:self; 25, identifier:_compute_dependency_order; 26, identifier:skills; 27, identifier:skill; 28, call; 29, subscript; 30, identifier:skill; 31, subscript; 32, identifier:sorted; 33, argument_list; 34, identifier:skill; 35, string; 36, subscript; 37, string; 38, identifier:skills; 39, keyword_argument; 40, string_content:learned; 41, attribute; 42, identifier:lang; 43, string_content:skills; 44, identifier:key; 45, lambda; 46, attribute; 47, identifier:language_data; 48, lambda_parameters; 49, subscript; 50, identifier:self; 51, identifier:user_data; 52, identifier:skill; 53, identifier:skill; 54, string; 55, string_content:dependency_order | 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; 12, 15; 12, 16; 13, 17; 13, 18; 14, 19; 14, 20; 14, 21; 16, 22; 16, 23; 17, 24; 17, 25; 18, 26; 20, 27; 20, 28; 21, 29; 23, 30; 23, 31; 28, 32; 28, 33; 29, 34; 29, 35; 31, 36; 31, 37; 33, 38; 33, 39; 35, 40; 36, 41; 36, 42; 37, 43; 39, 44; 39, 45; 41, 46; 41, 47; 45, 48; 45, 49; 46, 50; 46, 51; 48, 52; 49, 53; 49, 54; 54, 55 | def get_learned_skills(self, lang):
"""
Return the learned skill objects sorted by the order they were learned
in.
"""
skills = [skill for skill in
self.user_data.language_data[lang]['skills']]
self._compute_dependency_order(skills)
return [skill for skill in
sorted(skills, key=lambda skill: skill['dependency_order'])
if skill['learned']] |
0, module; 1, function_definition; 2, function_name:combine_adjacent_lines; 3, parameters; 4, block; 5, identifier:line_numbers; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, comment:# Add a terminating value of `None` to list; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, for_statement; 14, return_statement; 15, comment:"""
Given a sorted collection of line numbers this will
turn them to strings and combine adjacent values
[1, 2, 5, 6, 100] -> ["1-2", "5-6", "100"]
"""; 16, assignment; 17, assignment; 18, call; 19, assignment; 20, assignment; 21, identifier:line_number; 22, subscript; 23, comment:# If the current number is adjacent to the previous number; 24, block; 25, identifier:combined_list; 26, identifier:combine_template; 27, string:"{0}-{1}"; 28, identifier:combined_list; 29, list; 30, attribute; 31, argument_list; 32, identifier:start; 33, subscript; 34, identifier:end; 35, None; 36, identifier:line_numbers; 37, slice; 38, if_statement; 39, identifier:line_numbers; 40, identifier:append; 41, None; 42, identifier:line_numbers; 43, integer:0; 44, integer:1; 45, comparison_operator:(end if end else start) + 1 == line_number; 46, block; 47, else_clause; 48, binary_operator:(end if end else start) + 1; 49, identifier:line_number; 50, expression_statement; 51, block; 52, parenthesized_expression; 53, integer:1; 54, assignment; 55, if_statement; 56, expression_statement; 57, expression_statement; 58, conditional_expression:end if end else start; 59, identifier:end; 60, identifier:line_number; 61, identifier:end; 62, block; 63, else_clause; 64, assignment; 65, assignment; 66, identifier:end; 67, identifier:end; 68, identifier:start; 69, expression_statement; 70, block; 71, identifier:start; 72, identifier:line_number; 73, identifier:end; 74, None; 75, call; 76, expression_statement; 77, attribute; 78, argument_list; 79, call; 80, identifier:combined_list; 81, identifier:append; 82, call; 83, attribute; 84, argument_list; 85, attribute; 86, argument_list; 87, identifier:combined_list; 88, identifier:append; 89, call; 90, identifier:combine_template; 91, identifier:format; 92, identifier:start; 93, identifier:end; 94, identifier:str; 95, argument_list; 96, identifier:start | 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; 10, 18; 11, 19; 12, 20; 13, 21; 13, 22; 13, 23; 13, 24; 14, 25; 16, 26; 16, 27; 17, 28; 17, 29; 18, 30; 18, 31; 19, 32; 19, 33; 20, 34; 20, 35; 22, 36; 22, 37; 24, 38; 30, 39; 30, 40; 31, 41; 33, 42; 33, 43; 37, 44; 38, 45; 38, 46; 38, 47; 45, 48; 45, 49; 46, 50; 47, 51; 48, 52; 48, 53; 50, 54; 51, 55; 51, 56; 51, 57; 52, 58; 54, 59; 54, 60; 55, 61; 55, 62; 55, 63; 56, 64; 57, 65; 58, 66; 58, 67; 58, 68; 62, 69; 63, 70; 64, 71; 64, 72; 65, 73; 65, 74; 69, 75; 70, 76; 75, 77; 75, 78; 76, 79; 77, 80; 77, 81; 78, 82; 79, 83; 79, 84; 82, 85; 82, 86; 83, 87; 83, 88; 84, 89; 85, 90; 85, 91; 86, 92; 86, 93; 89, 94; 89, 95; 95, 96 | def combine_adjacent_lines(line_numbers):
"""
Given a sorted collection of line numbers this will
turn them to strings and combine adjacent values
[1, 2, 5, 6, 100] -> ["1-2", "5-6", "100"]
"""
combine_template = "{0}-{1}"
combined_list = []
# Add a terminating value of `None` to list
line_numbers.append(None)
start = line_numbers[0]
end = None
for line_number in line_numbers[1:]:
# If the current number is adjacent to the previous number
if (end if end else start) + 1 == line_number:
end = line_number
else:
if end:
combined_list.append(combine_template.format(start, end))
else:
combined_list.append(str(start))
start = line_number
end = None
return combined_list |
0, module; 1, function_definition; 2, function_name:sort_menus; 3, parameters; 4, block; 5, identifier:c; 6, expression_statement; 7, for_statement; 8, comment:"""
sort_menus goes through the items and sorts them based on
their weight
"""; 9, identifier:name; 10, attribute; 11, block; 12, identifier:c; 13, identifier:items; 14, if_statement; 15, not_operator; 16, block; 17, subscript; 18, expression_statement; 19, expression_statement; 20, attribute; 21, identifier:name; 22, call; 23, assignment; 24, identifier:c; 25, identifier:sorted; 26, attribute; 27, argument_list; 28, subscript; 29, True; 30, subscript; 31, identifier:sort; 32, keyword_argument; 33, attribute; 34, identifier:name; 35, attribute; 36, identifier:name; 37, identifier:key; 38, lambda; 39, identifier:c; 40, identifier:sorted; 41, identifier:c; 42, identifier:items; 43, lambda_parameters; 44, attribute; 45, identifier:x; 46, identifier:x; 47, identifier:weight | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 6, 8; 7, 9; 7, 10; 7, 11; 10, 12; 10, 13; 11, 14; 14, 15; 14, 16; 15, 17; 16, 18; 16, 19; 17, 20; 17, 21; 18, 22; 19, 23; 20, 24; 20, 25; 22, 26; 22, 27; 23, 28; 23, 29; 26, 30; 26, 31; 27, 32; 28, 33; 28, 34; 30, 35; 30, 36; 32, 37; 32, 38; 33, 39; 33, 40; 35, 41; 35, 42; 38, 43; 38, 44; 43, 45; 44, 46; 44, 47 | def sort_menus(c):
"""
sort_menus goes through the items and sorts them based on
their weight
"""
for name in c.items:
if not c.sorted[name]:
c.items[name].sort(key=lambda x: x.weight)
c.sorted[name] = True |
0, module; 1, function_definition; 2, function_name:_frequency_order_transform; 3, parameters; 4, block; 5, identifier:sets; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, return_statement; 13, comment:"""Transform tokens to integers according to global frequency order.
This step replaces all original tokens in the sets with integers, and
helps to speed up subsequent prefix filtering and similarity computation.
See Section 4.3.2 in the paper "A Primitive Operator for Similarity Joins
in Data Cleaning" by Chaudhuri et al..
Args:
sets (list): a list of sets, each entry is an iterable representing a
set.
Returns:
sets (list): a list of sets, each entry is a sorted Numpy array with
integer tokens replacing the tokens in the original set.
order (dict): a dictionary that maps token to its integer representation
in the frequency order.
"""; 14, call; 15, assignment; 16, assignment; 17, assignment; 18, call; 19, expression_list; 20, attribute; 21, argument_list; 22, identifier:counts; 23, call; 24, identifier:order; 25, call; 26, identifier:sets; 27, list_comprehension; 28, attribute; 29, argument_list; 30, identifier:sets; 31, identifier:order; 32, identifier:logging; 33, identifier:debug; 34, string:"Applying frequency order transform on tokens..."; 35, identifier:reversed; 36, argument_list; 37, identifier:dict; 38, generator_expression; 39, call; 40, for_in_clause; 41, identifier:logging; 42, identifier:debug; 43, string:"Done applying frequency order."; 44, call; 45, tuple; 46, for_in_clause; 47, attribute; 48, argument_list; 49, identifier:s; 50, identifier:sets; 51, attribute; 52, argument_list; 53, identifier:token; 54, identifier:i; 55, pattern_list; 56, call; 57, identifier:np; 58, identifier:sort; 59, list_comprehension; 60, call; 61, identifier:most_common; 62, identifier:i; 63, tuple_pattern; 64, identifier:enumerate; 65, argument_list; 66, subscript; 67, for_in_clause; 68, identifier:Counter; 69, generator_expression; 70, identifier:token; 71, identifier:_; 72, identifier:counts; 73, identifier:order; 74, identifier:token; 75, identifier:token; 76, identifier:s; 77, identifier:token; 78, for_in_clause; 79, for_in_clause; 80, identifier:s; 81, identifier:sets; 82, identifier:token; 83, identifier:s | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 6, 13; 7, 14; 8, 15; 9, 16; 10, 17; 11, 18; 12, 19; 14, 20; 14, 21; 15, 22; 15, 23; 16, 24; 16, 25; 17, 26; 17, 27; 18, 28; 18, 29; 19, 30; 19, 31; 20, 32; 20, 33; 21, 34; 23, 35; 23, 36; 25, 37; 25, 38; 27, 39; 27, 40; 28, 41; 28, 42; 29, 43; 36, 44; 38, 45; 38, 46; 39, 47; 39, 48; 40, 49; 40, 50; 44, 51; 44, 52; 45, 53; 45, 54; 46, 55; 46, 56; 47, 57; 47, 58; 48, 59; 51, 60; 51, 61; 55, 62; 55, 63; 56, 64; 56, 65; 59, 66; 59, 67; 60, 68; 60, 69; 63, 70; 63, 71; 65, 72; 66, 73; 66, 74; 67, 75; 67, 76; 69, 77; 69, 78; 69, 79; 78, 80; 78, 81; 79, 82; 79, 83 | def _frequency_order_transform(sets):
"""Transform tokens to integers according to global frequency order.
This step replaces all original tokens in the sets with integers, and
helps to speed up subsequent prefix filtering and similarity computation.
See Section 4.3.2 in the paper "A Primitive Operator for Similarity Joins
in Data Cleaning" by Chaudhuri et al..
Args:
sets (list): a list of sets, each entry is an iterable representing a
set.
Returns:
sets (list): a list of sets, each entry is a sorted Numpy array with
integer tokens replacing the tokens in the original set.
order (dict): a dictionary that maps token to its integer representation
in the frequency order.
"""
logging.debug("Applying frequency order transform on tokens...")
counts = reversed(Counter(token for s in sets for token in s).most_common())
order = dict((token, i) for i, (token, _) in enumerate(counts))
sets = [np.sort([order[token] for token in s]) for s in sets]
logging.debug("Done applying frequency order.")
return sets, order |
0, module; 1, function_definition; 2, function_name:to_numpy_vectors; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, default_parameter; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, expression_statement; 14, expression_statement; 15, expression_statement; 16, expression_statement; 17, expression_statement; 18, if_statement; 19, if_statement; 20, return_statement; 21, identifier:variable_order; 22, None; 23, identifier:dtype; 24, attribute; 25, identifier:index_dtype; 26, attribute; 27, identifier:sort_indices; 28, False; 29, comment:"""Convert a binary quadratic model to numpy arrays.
Args:
variable_order (iterable, optional):
If provided, labels the variables; otherwise, row/column indices are used.
dtype (:class:`numpy.dtype`, optional):
Data-type of the biases. By default, the data-type is inferred from the biases.
index_dtype (:class:`numpy.dtype`, optional):
Data-type of the indices. By default, the data-type is inferred from the labels.
sort_indices (bool, optional, default=False):
If True, the indices are sorted, first by row then by column. Otherwise they
match :attr:`~.BinaryQuadraticModel.quadratic`.
Returns:
:obj:`~numpy.ndarray`: A numpy array of the linear biases.
tuple: The quadratic biases in COOrdinate format.
:obj:`~numpy.ndarray`: A numpy array of the row indices of the quadratic matrix
entries
:obj:`~numpy.ndarray`: A numpy array of the column indices of the quadratic matrix
entries
:obj:`~numpy.ndarray`: A numpy array of the values of the quadratic matrix
entries
The offset
Examples:
>>> bqm = dimod.BinaryQuadraticModel({}, {(0, 1): .5, (3, 2): -1, (0, 3): 1.5}, 0.0, dimod.SPIN)
>>> lin, (i, j, vals), off = bqm.to_numpy_vectors(sort_indices=True)
>>> lin
array([0., 0., 0., 0.])
>>> i
array([0, 0, 2])
>>> j
array([1, 3, 3])
>>> vals
array([ 0.5, 1.5, -1. ])
"""; 30, assignment; 31, assignment; 32, assignment; 33, assignment; 34, assignment; 35, assignment; 36, assignment; 37, comparison_operator:variable_order is None; 38, block; 39, else_clause; 40, identifier:sort_indices; 41, comment:# row index should be less than col index, this handles upper-triangular vs lower-triangular; 42, block; 43, expression_list; 44, identifier:np; 45, identifier:float; 46, identifier:np; 47, identifier:int64; 48, identifier:linear; 49, attribute; 50, identifier:quadratic; 51, attribute; 52, identifier:num_variables; 53, call; 54, identifier:num_interactions; 55, call; 56, identifier:irow; 57, call; 58, identifier:icol; 59, call; 60, identifier:qdata; 61, call; 62, identifier:variable_order; 63, None; 64, try_statement; 65, comment:# we could speed this up a lot with cython; 66, for_statement; 67, block; 68, expression_statement; 69, if_statement; 70, comment:# sort lexigraphically; 71, expression_statement; 72, if_statement; 73, identifier:ldata; 74, tuple; 75, call; 76, identifier:self; 77, identifier:linear; 78, identifier:self; 79, identifier:quadratic; 80, identifier:len; 81, argument_list; 82, identifier:len; 83, argument_list; 84, attribute; 85, argument_list; 86, attribute; 87, argument_list; 88, attribute; 89, argument_list; 90, block; 91, except_clause; 92, pattern_list; 93, call; 94, block; 95, try_statement; 96, expression_statement; 97, comment:# we could speed this up a lot with cython; 98, for_statement; 99, assignment; 100, call; 101, comment:# in-place; 102, block; 103, assignment; 104, not_operator; 105, comment:# copy; 106, block; 107, identifier:irow; 108, identifier:icol; 109, identifier:qdata; 110, attribute; 111, argument_list; 112, identifier:linear; 113, identifier:quadratic; 114, identifier:np; 115, identifier:empty; 116, identifier:num_interactions; 117, keyword_argument; 118, identifier:np; 119, identifier:empty; 120, identifier:num_interactions; 121, keyword_argument; 122, identifier:np; 123, identifier:empty; 124, identifier:num_interactions; 125, keyword_argument; 126, expression_statement; 127, identifier:KeyError; 128, block; 129, identifier:idx; 130, tuple_pattern; 131, identifier:enumerate; 132, argument_list; 133, expression_statement; 134, expression_statement; 135, expression_statement; 136, block; 137, except_clause; 138, assignment; 139, pattern_list; 140, call; 141, block; 142, identifier:swaps; 143, comparison_operator:irow > icol; 144, attribute; 145, argument_list; 146, expression_statement; 147, identifier:order; 148, call; 149, call; 150, expression_statement; 151, expression_statement; 152, expression_statement; 153, attribute; 154, identifier:type; 155, attribute; 156, identifier:dtype; 157, identifier:index_dtype; 158, identifier:dtype; 159, identifier:index_dtype; 160, identifier:dtype; 161, identifier:dtype; 162, assignment; 163, raise_statement; 164, tuple_pattern; 165, identifier:bias; 166, call; 167, assignment; 168, assignment; 169, assignment; 170, expression_statement; 171, identifier:KeyError; 172, block; 173, identifier:label_to_idx; 174, dictionary_comprehension; 175, identifier:idx; 176, tuple_pattern; 177, identifier:enumerate; 178, argument_list; 179, expression_statement; 180, expression_statement; 181, expression_statement; 182, identifier:irow; 183, identifier:icol; 184, identifier:swaps; 185, identifier:any; 186, assignment; 187, attribute; 188, argument_list; 189, attribute; 190, argument_list; 191, assignment; 192, assignment; 193, assignment; 194, identifier:ldata; 195, identifier:dtype; 196, identifier:self; 197, identifier:offset; 198, identifier:ldata; 199, call; 200, call; 201, identifier:u; 202, identifier:v; 203, attribute; 204, argument_list; 205, subscript; 206, identifier:u; 207, subscript; 208, identifier:v; 209, subscript; 210, identifier:bias; 211, assignment; 212, raise_statement; 213, pair; 214, for_in_clause; 215, tuple_pattern; 216, identifier:bias; 217, call; 218, assignment; 219, assignment; 220, assignment; 221, pattern_list; 222, expression_list; 223, identifier:np; 224, identifier:lexsort; 225, tuple; 226, parenthesized_expression; 227, identifier:all; 228, identifier:irow; 229, subscript; 230, identifier:icol; 231, subscript; 232, identifier:qdata; 233, subscript; 234, attribute; 235, argument_list; 236, identifier:ValueError; 237, argument_list; 238, identifier:quadratic; 239, identifier:items; 240, identifier:irow; 241, identifier:idx; 242, identifier:icol; 243, identifier:idx; 244, identifier:qdata; 245, identifier:idx; 246, identifier:ldata; 247, call; 248, call; 249, identifier:v; 250, identifier:idx; 251, pattern_list; 252, call; 253, identifier:u; 254, identifier:v; 255, attribute; 256, argument_list; 257, subscript; 258, subscript; 259, subscript; 260, subscript; 261, subscript; 262, identifier:bias; 263, subscript; 264, subscript; 265, subscript; 266, subscript; 267, identifier:irow; 268, identifier:icol; 269, comparison_operator:order == range(len(order)); 270, identifier:irow; 271, identifier:order; 272, identifier:icol; 273, identifier:order; 274, identifier:qdata; 275, identifier:order; 276, identifier:np; 277, identifier:fromiter; 278, generator_expression; 279, keyword_argument; 280, keyword_argument; 281, parenthesized_expression; 282, attribute; 283, argument_list; 284, identifier:ValueError; 285, argument_list; 286, identifier:idx; 287, identifier:v; 288, identifier:enumerate; 289, argument_list; 290, identifier:quadratic; 291, identifier:items; 292, identifier:irow; 293, identifier:idx; 294, identifier:label_to_idx; 295, identifier:u; 296, identifier:icol; 297, identifier:idx; 298, identifier:label_to_idx; 299, identifier:v; 300, identifier:qdata; 301, identifier:idx; 302, identifier:irow; 303, identifier:swaps; 304, identifier:icol; 305, identifier:swaps; 306, identifier:icol; 307, identifier:swaps; 308, identifier:irow; 309, identifier:swaps; 310, identifier:order; 311, call; 312, subscript; 313, for_in_clause; 314, identifier:count; 315, identifier:num_variables; 316, identifier:dtype; 317, identifier:dtype; 318, concatenated_string; 319, identifier:np; 320, identifier:fromiter; 321, generator_expression; 322, keyword_argument; 323, keyword_argument; 324, string:"provided 'variable_order' does not match binary quadratic model"; 325, identifier:variable_order; 326, identifier:range; 327, argument_list; 328, identifier:linear; 329, identifier:v; 330, identifier:v; 331, call; 332, string:"if 'variable_order' is not provided, binary quadratic model must be "; 333, string:"index labeled [0, ..., N-1]"; 334, subscript; 335, for_in_clause; 336, identifier:count; 337, identifier:num_variables; 338, identifier:dtype; 339, identifier:dtype; 340, call; 341, identifier:range; 342, argument_list; 343, identifier:linear; 344, identifier:v; 345, identifier:v; 346, identifier:variable_order; 347, identifier:len; 348, argument_list; 349, identifier:num_variables; 350, identifier:order | 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; 6, 21; 6, 22; 7, 23; 7, 24; 8, 25; 8, 26; 9, 27; 9, 28; 10, 29; 11, 30; 12, 31; 13, 32; 14, 33; 15, 34; 16, 35; 17, 36; 18, 37; 18, 38; 18, 39; 19, 40; 19, 41; 19, 42; 20, 43; 24, 44; 24, 45; 26, 46; 26, 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; 36, 60; 36, 61; 37, 62; 37, 63; 38, 64; 38, 65; 38, 66; 39, 67; 42, 68; 42, 69; 42, 70; 42, 71; 42, 72; 43, 73; 43, 74; 43, 75; 49, 76; 49, 77; 51, 78; 51, 79; 53, 80; 53, 81; 55, 82; 55, 83; 57, 84; 57, 85; 59, 86; 59, 87; 61, 88; 61, 89; 64, 90; 64, 91; 66, 92; 66, 93; 66, 94; 67, 95; 67, 96; 67, 97; 67, 98; 68, 99; 69, 100; 69, 101; 69, 102; 71, 103; 72, 104; 72, 105; 72, 106; 74, 107; 74, 108; 74, 109; 75, 110; 75, 111; 81, 112; 83, 113; 84, 114; 84, 115; 85, 116; 85, 117; 86, 118; 86, 119; 87, 120; 87, 121; 88, 122; 88, 123; 89, 124; 89, 125; 90, 126; 91, 127; 91, 128; 92, 129; 92, 130; 93, 131; 93, 132; 94, 133; 94, 134; 94, 135; 95, 136; 95, 137; 96, 138; 98, 139; 98, 140; 98, 141; 99, 142; 99, 143; 100, 144; 100, 145; 102, 146; 103, 147; 103, 148; 104, 149; 106, 150; 106, 151; 106, 152; 110, 153; 110, 154; 111, 155; 117, 156; 117, 157; 121, 158; 121, 159; 125, 160; 125, 161; 126, 162; 128, 163; 130, 164; 130, 165; 132, 166; 133, 167; 134, 168; 135, 169; 136, 170; 137, 171; 137, 172; 138, 173; 138, 174; 139, 175; 139, 176; 140, 177; 140, 178; 141, 179; 141, 180; 141, 181; 143, 182; 143, 183; 144, 184; 144, 185; 146, 186; 148, 187; 148, 188; 149, 189; 149, 190; 150, 191; 151, 192; 152, 193; 153, 194; 153, 195; 155, 196; 155, 197; 162, 198; 162, 199; 163, 200; 164, 201; 164, 202; 166, 203; 166, 204; 167, 205; 167, 206; 168, 207; 168, 208; 169, 209; 169, 210; 170, 211; 172, 212; 174, 213; 174, 214; 176, 215; 176, 216; 178, 217; 179, 218; 180, 219; 181, 220; 186, 221; 186, 222; 187, 223; 187, 224; 188, 225; 189, 226; 189, 227; 191, 228; 191, 229; 192, 230; 192, 231; 193, 232; 193, 233; 199, 234; 199, 235; 200, 236; 200, 237; 203, 238; 203, 239; 205, 240; 205, 241; 207, 242; 207, 243; 209, 244; 209, 245; 211, 246; 211, 247; 212, 248; 213, 249; 213, 250; 214, 251; 214, 252; 215, 253; 215, 254; 217, 255; 217, 256; 218, 257; 218, 258; 219, 259; 219, 260; 220, 261; 220, 262; 221, 263; 221, 264; 222, 265; 222, 266; 225, 267; 225, 268; 226, 269; 229, 270; 229, 271; 231, 272; 231, 273; 233, 274; 233, 275; 234, 276; 234, 277; 235, 278; 235, 279; 235, 280; 237, 281; 247, 282; 247, 283; 248, 284; 248, 285; 251, 286; 251, 287; 252, 288; 252, 289; 255, 290; 255, 291; 257, 292; 257, 293; 258, 294; 258, 295; 259, 296; 259, 297; 260, 298; 260, 299; 261, 300; 261, 301; 263, 302; 263, 303; 264, 304; 264, 305; 265, 306; 265, 307; 266, 308; 266, 309; 269, 310; 269, 311; 278, 312; 278, 313; 279, 314; 279, 315; 280, 316; 280, 317; 281, 318; 282, 319; 282, 320; 283, 321; 283, 322; 283, 323; 285, 324; 289, 325; 311, 326; 311, 327; 312, 328; 312, 329; 313, 330; 313, 331; 318, 332; 318, 333; 321, 334; 321, 335; 322, 336; 322, 337; 323, 338; 323, 339; 327, 340; 331, 341; 331, 342; 334, 343; 334, 344; 335, 345; 335, 346; 340, 347; 340, 348; 342, 349; 348, 350 | def to_numpy_vectors(self, variable_order=None, dtype=np.float, index_dtype=np.int64, sort_indices=False):
"""Convert a binary quadratic model to numpy arrays.
Args:
variable_order (iterable, optional):
If provided, labels the variables; otherwise, row/column indices are used.
dtype (:class:`numpy.dtype`, optional):
Data-type of the biases. By default, the data-type is inferred from the biases.
index_dtype (:class:`numpy.dtype`, optional):
Data-type of the indices. By default, the data-type is inferred from the labels.
sort_indices (bool, optional, default=False):
If True, the indices are sorted, first by row then by column. Otherwise they
match :attr:`~.BinaryQuadraticModel.quadratic`.
Returns:
:obj:`~numpy.ndarray`: A numpy array of the linear biases.
tuple: The quadratic biases in COOrdinate format.
:obj:`~numpy.ndarray`: A numpy array of the row indices of the quadratic matrix
entries
:obj:`~numpy.ndarray`: A numpy array of the column indices of the quadratic matrix
entries
:obj:`~numpy.ndarray`: A numpy array of the values of the quadratic matrix
entries
The offset
Examples:
>>> bqm = dimod.BinaryQuadraticModel({}, {(0, 1): .5, (3, 2): -1, (0, 3): 1.5}, 0.0, dimod.SPIN)
>>> lin, (i, j, vals), off = bqm.to_numpy_vectors(sort_indices=True)
>>> lin
array([0., 0., 0., 0.])
>>> i
array([0, 0, 2])
>>> j
array([1, 3, 3])
>>> vals
array([ 0.5, 1.5, -1. ])
"""
linear = self.linear
quadratic = self.quadratic
num_variables = len(linear)
num_interactions = len(quadratic)
irow = np.empty(num_interactions, dtype=index_dtype)
icol = np.empty(num_interactions, dtype=index_dtype)
qdata = np.empty(num_interactions, dtype=dtype)
if variable_order is None:
try:
ldata = np.fromiter((linear[v] for v in range(num_variables)), count=num_variables, dtype=dtype)
except KeyError:
raise ValueError(("if 'variable_order' is not provided, binary quadratic model must be "
"index labeled [0, ..., N-1]"))
# we could speed this up a lot with cython
for idx, ((u, v), bias) in enumerate(quadratic.items()):
irow[idx] = u
icol[idx] = v
qdata[idx] = bias
else:
try:
ldata = np.fromiter((linear[v] for v in variable_order), count=num_variables, dtype=dtype)
except KeyError:
raise ValueError("provided 'variable_order' does not match binary quadratic model")
label_to_idx = {v: idx for idx, v in enumerate(variable_order)}
# we could speed this up a lot with cython
for idx, ((u, v), bias) in enumerate(quadratic.items()):
irow[idx] = label_to_idx[u]
icol[idx] = label_to_idx[v]
qdata[idx] = bias
if sort_indices:
# row index should be less than col index, this handles upper-triangular vs lower-triangular
swaps = irow > icol
if swaps.any():
# in-place
irow[swaps], icol[swaps] = icol[swaps], irow[swaps]
# sort lexigraphically
order = np.lexsort((irow, icol))
if not (order == range(len(order))).all():
# copy
irow = irow[order]
icol = icol[order]
qdata = qdata[order]
return ldata, (irow, icol, qdata), ldata.dtype.type(self.offset) |
0, module; 1, function_definition; 2, function_name:from_samples_bqm; 3, parameters; 4, block; 5, identifier:cls; 6, identifier:samples_like; 7, identifier:bqm; 8, dictionary_splat_pattern; 9, expression_statement; 10, comment:# more performant to do this once, here rather than again in bqm.energies; 11, comment:# and in cls.from_samples; 12, expression_statement; 13, expression_statement; 14, return_statement; 15, identifier:kwargs; 16, comment:"""Build a SampleSet from raw samples using a BinaryQuadraticModel to get energies and vartype.
Args:
samples_like:
A collection of raw samples. 'samples_like' is an extension of NumPy's array_like.
See :func:`.as_samples`.
bqm (:obj:`.BinaryQuadraticModel`):
A binary quadratic model. It is used to calculate the energies
and set the vartype.
info (dict, optional):
Information about the :class:`SampleSet` as a whole formatted as a dict.
num_occurrences (array_like, optional):
Number of occurrences for each sample. If not provided, defaults to a vector of 1s.
aggregate_samples (bool, optional, default=False):
If true, returned :obj:`.SampleSet` will have all unique samples.
sort_labels (bool, optional, default=True):
If true, :attr:`.SampleSet.variables` will be in sorted-order.
Note that mixed types are not sortable in which case the given
order will be maintained.
**vectors (array_like):
Other per-sample data.
Returns:
:obj:`.SampleSet`
Examples:
>>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): -1})
>>> samples = dimod.SampleSet.from_samples_bqm({'a': -1, 'b': 1}, bqm)
"""; 17, assignment; 18, assignment; 19, call; 20, identifier:samples_like; 21, call; 22, identifier:energies; 23, call; 24, attribute; 25, argument_list; 26, identifier:as_samples; 27, argument_list; 28, attribute; 29, argument_list; 30, identifier:cls; 31, identifier:from_samples; 32, identifier:samples_like; 33, keyword_argument; 34, keyword_argument; 35, dictionary_splat; 36, identifier:samples_like; 37, identifier:bqm; 38, identifier:energies; 39, identifier:samples_like; 40, identifier:energy; 41, identifier:energies; 42, identifier:vartype; 43, attribute; 44, identifier:kwargs; 45, identifier:bqm; 46, identifier:vartype | 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; 8, 15; 9, 16; 12, 17; 13, 18; 14, 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; 25, 34; 25, 35; 27, 36; 28, 37; 28, 38; 29, 39; 33, 40; 33, 41; 34, 42; 34, 43; 35, 44; 43, 45; 43, 46 | def from_samples_bqm(cls, samples_like, bqm, **kwargs):
"""Build a SampleSet from raw samples using a BinaryQuadraticModel to get energies and vartype.
Args:
samples_like:
A collection of raw samples. 'samples_like' is an extension of NumPy's array_like.
See :func:`.as_samples`.
bqm (:obj:`.BinaryQuadraticModel`):
A binary quadratic model. It is used to calculate the energies
and set the vartype.
info (dict, optional):
Information about the :class:`SampleSet` as a whole formatted as a dict.
num_occurrences (array_like, optional):
Number of occurrences for each sample. If not provided, defaults to a vector of 1s.
aggregate_samples (bool, optional, default=False):
If true, returned :obj:`.SampleSet` will have all unique samples.
sort_labels (bool, optional, default=True):
If true, :attr:`.SampleSet.variables` will be in sorted-order.
Note that mixed types are not sortable in which case the given
order will be maintained.
**vectors (array_like):
Other per-sample data.
Returns:
:obj:`.SampleSet`
Examples:
>>> bqm = dimod.BinaryQuadraticModel.from_ising({}, {('a', 'b'): -1})
>>> samples = dimod.SampleSet.from_samples_bqm({'a': -1, 'b': 1}, bqm)
"""
# more performant to do this once, here rather than again in bqm.energies
# and in cls.from_samples
samples_like = as_samples(samples_like)
energies = bqm.energies(samples_like)
return cls.from_samples(samples_like, energy=energies, vartype=bqm.vartype, **kwargs) |
0, module; 1, function_definition; 2, function_name:samples; 3, parameters; 4, block; 5, identifier:self; 6, default_parameter; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, if_statement; 11, return_statement; 12, identifier:n; 13, None; 14, identifier:sorted_by; 15, string; 16, comment:"""Return an iterable over the samples.
Args:
n (int, optional, default=None):
Maximum number of samples to return in the view.
sorted_by (str/None, optional, default='energy'):
Selects the record field used to sort the samples. If None,
samples are returned in record order.
Returns:
:obj:`.SamplesArray`: A view object mapping variable labels to
values.
Examples:
>>> sampleset = dimod.ExactSolver().sample_ising({'a': 0.1, 'b': 0.0},
... {('a', 'b'): 1})
>>> for sample in sampleset.samples():
... print(sample)
{'a': -1, 'b': 1}
{'a': 1, 'b': -1}
{'a': -1, 'b': -1}
{'a': 1, 'b': 1}
>>> sampleset = dimod.ExactSolver().sample_ising({'a': 0.1, 'b': 0.0},
... {('a', 'b'): 1})
>>> samples = sampleset.samples()
>>> samples[0]
{'a': -1, 'b': 1}
>>> samples[0, 'a']
-1
>>> samples[0, ['b', 'a']]
array([ 1, -1], dtype=int8)
>>> samples[1:, ['a', 'b']]
array([[ 1, -1],
[-1, -1],
[ 1, 1]], dtype=int8)
"""; 17, comparison_operator:n is not None; 18, block; 19, comparison_operator:sorted_by is None; 20, block; 21, else_clause; 22, call; 23, string_content:energy; 24, identifier:n; 25, None; 26, return_statement; 27, identifier:sorted_by; 28, None; 29, expression_statement; 30, block; 31, identifier:SamplesArray; 32, argument_list; 33, subscript; 34, assignment; 35, expression_statement; 36, expression_statement; 37, identifier:samples; 38, attribute; 39, call; 40, slice; 41, identifier:samples; 42, attribute; 43, assignment; 44, assignment; 45, identifier:self; 46, identifier:variables; 47, attribute; 48, argument_list; 49, identifier:n; 50, attribute; 51, identifier:sample; 52, identifier:order; 53, call; 54, identifier:samples; 55, subscript; 56, identifier:self; 57, identifier:samples; 58, keyword_argument; 59, identifier:self; 60, identifier:record; 61, attribute; 62, argument_list; 63, attribute; 64, identifier:order; 65, identifier:sorted_by; 66, identifier:sorted_by; 67, identifier:np; 68, identifier:argsort; 69, subscript; 70, attribute; 71, identifier:sample; 72, attribute; 73, identifier:sorted_by; 74, identifier:self; 75, identifier:record; 76, identifier:self; 77, identifier:record | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 4, 10; 4, 11; 6, 12; 6, 13; 7, 14; 7, 15; 8, 16; 9, 17; 9, 18; 10, 19; 10, 20; 10, 21; 11, 22; 15, 23; 17, 24; 17, 25; 18, 26; 19, 27; 19, 28; 20, 29; 21, 30; 22, 31; 22, 32; 26, 33; 29, 34; 30, 35; 30, 36; 32, 37; 32, 38; 33, 39; 33, 40; 34, 41; 34, 42; 35, 43; 36, 44; 38, 45; 38, 46; 39, 47; 39, 48; 40, 49; 42, 50; 42, 51; 43, 52; 43, 53; 44, 54; 44, 55; 47, 56; 47, 57; 48, 58; 50, 59; 50, 60; 53, 61; 53, 62; 55, 63; 55, 64; 58, 65; 58, 66; 61, 67; 61, 68; 62, 69; 63, 70; 63, 71; 69, 72; 69, 73; 70, 74; 70, 75; 72, 76; 72, 77 | def samples(self, n=None, sorted_by='energy'):
"""Return an iterable over the samples.
Args:
n (int, optional, default=None):
Maximum number of samples to return in the view.
sorted_by (str/None, optional, default='energy'):
Selects the record field used to sort the samples. If None,
samples are returned in record order.
Returns:
:obj:`.SamplesArray`: A view object mapping variable labels to
values.
Examples:
>>> sampleset = dimod.ExactSolver().sample_ising({'a': 0.1, 'b': 0.0},
... {('a', 'b'): 1})
>>> for sample in sampleset.samples():
... print(sample)
{'a': -1, 'b': 1}
{'a': 1, 'b': -1}
{'a': -1, 'b': -1}
{'a': 1, 'b': 1}
>>> sampleset = dimod.ExactSolver().sample_ising({'a': 0.1, 'b': 0.0},
... {('a', 'b'): 1})
>>> samples = sampleset.samples()
>>> samples[0]
{'a': -1, 'b': 1}
>>> samples[0, 'a']
-1
>>> samples[0, ['b', 'a']]
array([ 1, -1], dtype=int8)
>>> samples[1:, ['a', 'b']]
array([[ 1, -1],
[-1, -1],
[ 1, 1]], dtype=int8)
"""
if n is not None:
return self.samples(sorted_by=sorted_by)[:n]
if sorted_by is None:
samples = self.record.sample
else:
order = np.argsort(self.record[sorted_by])
samples = self.record.sample[order]
return SamplesArray(samples, self.variables) |
0, module; 1, function_definition; 2, function_name:append_variables; 3, parameters; 4, block; 5, identifier:self; 6, identifier:samples_like; 7, default_parameter; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, comment:# we don't handle multiple values; 12, if_statement; 13, comment:# append requires the new variables to be unique; 14, expression_statement; 15, if_statement; 16, expression_statement; 17, expression_statement; 18, return_statement; 19, identifier:sort_labels; 20, True; 21, comment:"""Create a new sampleset with the given variables with values added.
Not defined for empty sample sets. Note that when `sample_like` is
a :obj:`.SampleSet`, the data vectors and info are ignored.
Args:
samples_like:
Samples to add to the sample set. Should either be a single
sample or should match the length of the sample set. See
:func:`.as_samples` for what is allowed to be `samples_like`.
sort_labels (bool, optional, default=True):
If true, returned :attr:`.SampleSet.variables` will be in
sorted-order. Note that mixed types are not sortable in which
case the given order will be maintained.
Returns:
:obj:`.SampleSet`: A new sample set with the variables/values added.
Examples:
>>> sampleset = dimod.SampleSet.from_samples([{'a': -1, 'b': +1},
... {'a': +1, 'b': +1}],
... dimod.SPIN,
... energy=[-1.0, 1.0])
>>> new = sampleset.append_variables({'c': -1})
>>> print(new)
a b c energy num_oc.
0 -1 +1 -1 -1.0 1
1 +1 +1 -1 1.0 1
['SPIN', 2 rows, 2 samples, 3 variables]
Add variables from another sampleset to the original above. Note
that the energies do not change.
>>> another = dimod.SampleSet.from_samples([{'c': -1, 'd': +1},
... {'c': +1, 'd': +1}],
... dimod.SPIN,
... energy=[-2.0, 1.0])
>>> new = sampleset.append_variables(another)
>>> print(new)
a b c d energy num_oc.
0 -1 +1 -1 +1 -1.0 1
1 +1 +1 +1 +1 1.0 1
['SPIN', 2 rows, 2 samples, 4 variables]
"""; 22, assignment; 23, assignment; 24, comparison_operator:samples.shape[0] == num_samples; 25, comment:# we don't need to do anything, it's already the correct shape; 26, block; 27, elif_clause; 28, else_clause; 29, assignment; 30, call; 31, block; 32, assignment; 33, assignment; 34, call; 35, pattern_list; 36, call; 37, identifier:num_samples; 38, call; 39, subscript; 40, identifier:num_samples; 41, pass_statement; 42, boolean_operator; 43, block; 44, block; 45, identifier:variables; 46, attribute; 47, identifier:any; 48, generator_expression; 49, expression_statement; 50, raise_statement; 51, identifier:new_variables; 52, binary_operator:list(variables) + labels; 53, identifier:new_samples; 54, call; 55, attribute; 56, argument_list; 57, identifier:samples; 58, identifier:labels; 59, identifier:as_samples; 60, argument_list; 61, identifier:len; 62, argument_list; 63, attribute; 64, integer:0; 65, comparison_operator:samples.shape[0] == 1; 66, identifier:num_samples; 67, expression_statement; 68, expression_statement; 69, raise_statement; 70, identifier:self; 71, identifier:variables; 72, comparison_operator:v in variables; 73, for_in_clause; 74, assignment; 75, call; 76, call; 77, identifier:labels; 78, attribute; 79, argument_list; 80, call; 81, identifier:from_samples; 82, tuple; 83, attribute; 84, keyword_argument; 85, comment:# make a copy; 86, keyword_argument; 87, dictionary_splat; 88, identifier:samples_like; 89, identifier:self; 90, identifier:samples; 91, identifier:shape; 92, subscript; 93, integer:1; 94, assignment; 95, assignment; 96, call; 97, identifier:v; 98, identifier:variables; 99, identifier:v; 100, identifier:labels; 101, identifier:msg; 102, string:"Appended samples cannot contain variables in sample set"; 103, identifier:ValueError; 104, argument_list; 105, identifier:list; 106, argument_list; 107, identifier:np; 108, identifier:hstack; 109, tuple; 110, identifier:type; 111, argument_list; 112, identifier:new_samples; 113, identifier:new_variables; 114, identifier:self; 115, identifier:vartype; 116, identifier:info; 117, call; 118, identifier:sort_labels; 119, identifier:sort_labels; 120, attribute; 121, attribute; 122, integer:0; 123, identifier:samples; 124, call; 125, identifier:msg; 126, parenthesized_expression; 127, identifier:ValueError; 128, argument_list; 129, identifier:msg; 130, identifier:variables; 131, attribute; 132, identifier:samples; 133, identifier:self; 134, attribute; 135, argument_list; 136, identifier:self; 137, identifier:data_vectors; 138, identifier:samples; 139, identifier:shape; 140, attribute; 141, argument_list; 142, concatenated_string; 143, identifier:msg; 144, attribute; 145, identifier:sample; 146, identifier:copy; 147, identifier:deepcopy; 148, attribute; 149, identifier:np; 150, identifier:repeat; 151, identifier:samples; 152, identifier:num_samples; 153, keyword_argument; 154, string:"mismatched shape. The samples to append should either be "; 155, string:"a single sample or should match the length of the sample "; 156, string:"set. Empty sample sets cannot be appended to."; 157, identifier:self; 158, identifier:record; 159, identifier:self; 160, identifier:info; 161, identifier:axis; 162, integer:0 | 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; 7, 19; 7, 20; 8, 21; 9, 22; 10, 23; 12, 24; 12, 25; 12, 26; 12, 27; 12, 28; 14, 29; 15, 30; 15, 31; 16, 32; 17, 33; 18, 34; 22, 35; 22, 36; 23, 37; 23, 38; 24, 39; 24, 40; 26, 41; 27, 42; 27, 43; 28, 44; 29, 45; 29, 46; 30, 47; 30, 48; 31, 49; 31, 50; 32, 51; 32, 52; 33, 53; 33, 54; 34, 55; 34, 56; 35, 57; 35, 58; 36, 59; 36, 60; 38, 61; 38, 62; 39, 63; 39, 64; 42, 65; 42, 66; 43, 67; 44, 68; 44, 69; 46, 70; 46, 71; 48, 72; 48, 73; 49, 74; 50, 75; 52, 76; 52, 77; 54, 78; 54, 79; 55, 80; 55, 81; 56, 82; 56, 83; 56, 84; 56, 85; 56, 86; 56, 87; 60, 88; 62, 89; 63, 90; 63, 91; 65, 92; 65, 93; 67, 94; 68, 95; 69, 96; 72, 97; 72, 98; 73, 99; 73, 100; 74, 101; 74, 102; 75, 103; 75, 104; 76, 105; 76, 106; 78, 107; 78, 108; 79, 109; 80, 110; 80, 111; 82, 112; 82, 113; 83, 114; 83, 115; 84, 116; 84, 117; 86, 118; 86, 119; 87, 120; 92, 121; 92, 122; 94, 123; 94, 124; 95, 125; 95, 126; 96, 127; 96, 128; 104, 129; 106, 130; 109, 131; 109, 132; 111, 133; 117, 134; 117, 135; 120, 136; 120, 137; 121, 138; 121, 139; 124, 140; 124, 141; 126, 142; 128, 143; 131, 144; 131, 145; 134, 146; 134, 147; 135, 148; 140, 149; 140, 150; 141, 151; 141, 152; 141, 153; 142, 154; 142, 155; 142, 156; 144, 157; 144, 158; 148, 159; 148, 160; 153, 161; 153, 162 | def append_variables(self, samples_like, sort_labels=True):
"""Create a new sampleset with the given variables with values added.
Not defined for empty sample sets. Note that when `sample_like` is
a :obj:`.SampleSet`, the data vectors and info are ignored.
Args:
samples_like:
Samples to add to the sample set. Should either be a single
sample or should match the length of the sample set. See
:func:`.as_samples` for what is allowed to be `samples_like`.
sort_labels (bool, optional, default=True):
If true, returned :attr:`.SampleSet.variables` will be in
sorted-order. Note that mixed types are not sortable in which
case the given order will be maintained.
Returns:
:obj:`.SampleSet`: A new sample set with the variables/values added.
Examples:
>>> sampleset = dimod.SampleSet.from_samples([{'a': -1, 'b': +1},
... {'a': +1, 'b': +1}],
... dimod.SPIN,
... energy=[-1.0, 1.0])
>>> new = sampleset.append_variables({'c': -1})
>>> print(new)
a b c energy num_oc.
0 -1 +1 -1 -1.0 1
1 +1 +1 -1 1.0 1
['SPIN', 2 rows, 2 samples, 3 variables]
Add variables from another sampleset to the original above. Note
that the energies do not change.
>>> another = dimod.SampleSet.from_samples([{'c': -1, 'd': +1},
... {'c': +1, 'd': +1}],
... dimod.SPIN,
... energy=[-2.0, 1.0])
>>> new = sampleset.append_variables(another)
>>> print(new)
a b c d energy num_oc.
0 -1 +1 -1 +1 -1.0 1
1 +1 +1 +1 +1 1.0 1
['SPIN', 2 rows, 2 samples, 4 variables]
"""
samples, labels = as_samples(samples_like)
num_samples = len(self)
# we don't handle multiple values
if samples.shape[0] == num_samples:
# we don't need to do anything, it's already the correct shape
pass
elif samples.shape[0] == 1 and num_samples:
samples = np.repeat(samples, num_samples, axis=0)
else:
msg = ("mismatched shape. The samples to append should either be "
"a single sample or should match the length of the sample "
"set. Empty sample sets cannot be appended to.")
raise ValueError(msg)
# append requires the new variables to be unique
variables = self.variables
if any(v in variables for v in labels):
msg = "Appended samples cannot contain variables in sample set"
raise ValueError(msg)
new_variables = list(variables) + labels
new_samples = np.hstack((self.record.sample, samples))
return type(self).from_samples((new_samples, new_variables),
self.vartype,
info=copy.deepcopy(self.info), # make a copy
sort_labels=sort_labels,
**self.data_vectors) |
0, module; 1, function_definition; 2, function_name:slice; 3, parameters; 4, block; 5, identifier:self; 6, list_splat_pattern; 7, dictionary_splat_pattern; 8, expression_statement; 9, comment:# handle `sorted_by` kwarg with a default value in a python2-compatible way; 10, expression_statement; 11, if_statement; 12, comment:# follow Python's slice syntax; 13, if_statement; 14, if_statement; 15, return_statement; 16, identifier:slice_args; 17, identifier:kwargs; 18, comment:"""Create a new SampleSet with rows sliced according to standard Python
slicing syntax.
Args:
start (int, optional, default=None):
Start index for `slice`.
stop (int):
Stop index for `slice`.
step (int, optional, default=None):
Step value for `slice`.
sorted_by (str/None, optional, default='energy'):
Selects the record field used to sort the samples before
slicing. Note that `sorted_by` determines the sample order in
the returned SampleSet.
Returns:
:obj:`.SampleSet`
Examples:
>>> import numpy as np
...
>>> sampleset = dimod.SampleSet.from_samples(np.diag(range(1, 11)), dimod.BINARY, energy=range(10))
>>> print(sampleset)
0 1 2 3 4 5 6 7 8 9 energy num_oc.
0 1 0 0 0 0 0 0 0 0 0 0 1
1 0 1 0 0 0 0 0 0 0 0 1 1
2 0 0 1 0 0 0 0 0 0 0 2 1
3 0 0 0 1 0 0 0 0 0 0 3 1
4 0 0 0 0 1 0 0 0 0 0 4 1
5 0 0 0 0 0 1 0 0 0 0 5 1
6 0 0 0 0 0 0 1 0 0 0 6 1
7 0 0 0 0 0 0 0 1 0 0 7 1
8 0 0 0 0 0 0 0 0 1 0 8 1
9 0 0 0 0 0 0 0 0 0 1 9 1
['BINARY', 10 rows, 10 samples, 10 variables]
>>> # the first 3 samples by energy == truncate(3)
>>> print(sampleset.slice(3))
0 1 2 3 4 5 6 7 8 9 energy num_oc.
0 1 0 0 0 0 0 0 0 0 0 0 1
1 0 1 0 0 0 0 0 0 0 0 1 1
2 0 0 1 0 0 0 0 0 0 0 2 1
['BINARY', 3 rows, 3 samples, 10 variables]
>>> # the last 3 samples by energy
>>> print(sampleset.slice(-3, None))
0 1 2 3 4 5 6 7 8 9 energy num_oc.
0 0 0 0 0 0 0 0 1 0 0 7 1
1 0 0 0 0 0 0 0 0 1 0 8 1
2 0 0 0 0 0 0 0 0 0 1 9 1
['BINARY', 3 rows, 3 samples, 10 variables]
>>> # every second sample in between (skip the top and the bottom 3)
>>> print(sampleset.slice(3, -3, 2))
0 1 2 3 4 5 6 7 8 9 energy num_oc.
0 0 0 0 1 0 0 0 0 0 0 3 1
1 0 0 0 0 0 1 0 0 0 0 5 1
['BINARY', 2 rows, 2 samples, 10 variables]
"""; 19, assignment; 20, identifier:kwargs; 21, comment:# be strict about allowed kwargs: throw the same error as python3 would; 22, block; 23, identifier:slice_args; 24, block; 25, else_clause; 26, comparison_operator:sorted_by is None; 27, block; 28, else_clause; 29, call; 30, identifier:sorted_by; 31, call; 32, raise_statement; 33, expression_statement; 34, block; 35, identifier:sorted_by; 36, None; 37, expression_statement; 38, block; 39, call; 40, argument_list; 41, attribute; 42, argument_list; 43, call; 44, assignment; 45, expression_statement; 46, assignment; 47, expression_statement; 48, expression_statement; 49, identifier:type; 50, argument_list; 51, identifier:record; 52, attribute; 53, call; 54, attribute; 55, identifier:kwargs; 56, identifier:pop; 57, string; 58, string; 59, identifier:TypeError; 60, argument_list; 61, identifier:selector; 62, call; 63, assignment; 64, identifier:record; 65, subscript; 66, assignment; 67, assignment; 68, identifier:self; 69, identifier:self; 70, identifier:variables; 71, attribute; 72, argument_list; 73, identifier:self; 74, identifier:vartype; 75, string_content:sorted_by; 76, string_content:energy; 77, call; 78, identifier:slice; 79, argument_list; 80, identifier:selector; 81, call; 82, attribute; 83, identifier:selector; 84, identifier:sort_indices; 85, call; 86, identifier:record; 87, subscript; 88, identifier:copy; 89, identifier:deepcopy; 90, attribute; 91, attribute; 92, argument_list; 93, list_splat; 94, identifier:slice; 95, argument_list; 96, identifier:self; 97, identifier:record; 98, attribute; 99, argument_list; 100, attribute; 101, subscript; 102, identifier:self; 103, identifier:info; 104, concatenated_string; 105, identifier:format; 106, subscript; 107, identifier:slice_args; 108, None; 109, identifier:np; 110, identifier:argsort; 111, subscript; 112, identifier:self; 113, identifier:record; 114, identifier:sort_indices; 115, identifier:selector; 116, string; 117, string; 118, call; 119, integer:0; 120, attribute; 121, identifier:sorted_by; 122, string_content:slice got an unexpected; 123, string_content:keyword argument {!r}; 124, attribute; 125, argument_list; 126, identifier:self; 127, identifier:record; 128, identifier:kwargs; 129, identifier:popitem | 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; 6, 16; 7, 17; 8, 18; 10, 19; 11, 20; 11, 21; 11, 22; 13, 23; 13, 24; 13, 25; 14, 26; 14, 27; 14, 28; 15, 29; 19, 30; 19, 31; 22, 32; 24, 33; 25, 34; 26, 35; 26, 36; 27, 37; 28, 38; 29, 39; 29, 40; 31, 41; 31, 42; 32, 43; 33, 44; 34, 45; 37, 46; 38, 47; 38, 48; 39, 49; 39, 50; 40, 51; 40, 52; 40, 53; 40, 54; 41, 55; 41, 56; 42, 57; 42, 58; 43, 59; 43, 60; 44, 61; 44, 62; 45, 63; 46, 64; 46, 65; 47, 66; 48, 67; 50, 68; 52, 69; 52, 70; 53, 71; 53, 72; 54, 73; 54, 74; 57, 75; 58, 76; 60, 77; 62, 78; 62, 79; 63, 80; 63, 81; 65, 82; 65, 83; 66, 84; 66, 85; 67, 86; 67, 87; 71, 88; 71, 89; 72, 90; 77, 91; 77, 92; 79, 93; 81, 94; 81, 95; 82, 96; 82, 97; 85, 98; 85, 99; 87, 100; 87, 101; 90, 102; 90, 103; 91, 104; 91, 105; 92, 106; 93, 107; 95, 108; 98, 109; 98, 110; 99, 111; 100, 112; 100, 113; 101, 114; 101, 115; 104, 116; 104, 117; 106, 118; 106, 119; 111, 120; 111, 121; 116, 122; 117, 123; 118, 124; 118, 125; 120, 126; 120, 127; 124, 128; 124, 129 | def slice(self, *slice_args, **kwargs):
"""Create a new SampleSet with rows sliced according to standard Python
slicing syntax.
Args:
start (int, optional, default=None):
Start index for `slice`.
stop (int):
Stop index for `slice`.
step (int, optional, default=None):
Step value for `slice`.
sorted_by (str/None, optional, default='energy'):
Selects the record field used to sort the samples before
slicing. Note that `sorted_by` determines the sample order in
the returned SampleSet.
Returns:
:obj:`.SampleSet`
Examples:
>>> import numpy as np
...
>>> sampleset = dimod.SampleSet.from_samples(np.diag(range(1, 11)), dimod.BINARY, energy=range(10))
>>> print(sampleset)
0 1 2 3 4 5 6 7 8 9 energy num_oc.
0 1 0 0 0 0 0 0 0 0 0 0 1
1 0 1 0 0 0 0 0 0 0 0 1 1
2 0 0 1 0 0 0 0 0 0 0 2 1
3 0 0 0 1 0 0 0 0 0 0 3 1
4 0 0 0 0 1 0 0 0 0 0 4 1
5 0 0 0 0 0 1 0 0 0 0 5 1
6 0 0 0 0 0 0 1 0 0 0 6 1
7 0 0 0 0 0 0 0 1 0 0 7 1
8 0 0 0 0 0 0 0 0 1 0 8 1
9 0 0 0 0 0 0 0 0 0 1 9 1
['BINARY', 10 rows, 10 samples, 10 variables]
>>> # the first 3 samples by energy == truncate(3)
>>> print(sampleset.slice(3))
0 1 2 3 4 5 6 7 8 9 energy num_oc.
0 1 0 0 0 0 0 0 0 0 0 0 1
1 0 1 0 0 0 0 0 0 0 0 1 1
2 0 0 1 0 0 0 0 0 0 0 2 1
['BINARY', 3 rows, 3 samples, 10 variables]
>>> # the last 3 samples by energy
>>> print(sampleset.slice(-3, None))
0 1 2 3 4 5 6 7 8 9 energy num_oc.
0 0 0 0 0 0 0 0 1 0 0 7 1
1 0 0 0 0 0 0 0 0 1 0 8 1
2 0 0 0 0 0 0 0 0 0 1 9 1
['BINARY', 3 rows, 3 samples, 10 variables]
>>> # every second sample in between (skip the top and the bottom 3)
>>> print(sampleset.slice(3, -3, 2))
0 1 2 3 4 5 6 7 8 9 energy num_oc.
0 0 0 0 1 0 0 0 0 0 0 3 1
1 0 0 0 0 0 1 0 0 0 0 5 1
['BINARY', 2 rows, 2 samples, 10 variables]
"""
# handle `sorted_by` kwarg with a default value in a python2-compatible way
sorted_by = kwargs.pop('sorted_by', 'energy')
if kwargs:
# be strict about allowed kwargs: throw the same error as python3 would
raise TypeError('slice got an unexpected '
'keyword argument {!r}'.format(kwargs.popitem()[0]))
# follow Python's slice syntax
if slice_args:
selector = slice(*slice_args)
else:
selector = slice(None)
if sorted_by is None:
record = self.record[selector]
else:
sort_indices = np.argsort(self.record[sorted_by])
record = self.record[sort_indices[selector]]
return type(self)(record, self.variables, copy.deepcopy(self.info),
self.vartype) |
0, module; 1, function_definition; 2, function_name:describe_features; 3, parameters; 4, block; 5, identifier:self; 6, identifier:traj; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, return_statement; 11, comment:"""Generic method for describing features.
Parameters
----------
traj : mdtraj.Trajectory
Trajectory to use
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Featurizer name
- featuregroup: Other information
Notes
-------
Method resorts to returning N/A for everything if describe_features in not
implemented in the sub_class
"""; 12, assignment; 13, assignment; 14, call; 15, identifier:n_f; 16, subscript; 17, identifier:zippy; 18, call; 19, identifier:dict_maker; 20, argument_list; 21, attribute; 22, integer:1; 23, identifier:zip; 24, argument_list; 25, identifier:zippy; 26, call; 27, identifier:shape; 28, call; 29, call; 30, call; 31, call; 32, attribute; 33, argument_list; 34, attribute; 35, argument_list; 36, attribute; 37, argument_list; 38, attribute; 39, argument_list; 40, attribute; 41, argument_list; 42, identifier:self; 43, identifier:partial_transform; 44, identifier:traj; 45, identifier:itertools; 46, identifier:repeat; 47, string:"N/A"; 48, identifier:n_f; 49, identifier:itertools; 50, identifier:repeat; 51, string:"N/A"; 52, identifier:n_f; 53, identifier:itertools; 54, identifier:repeat; 55, string:"N/A"; 56, identifier:n_f; 57, identifier:itertools; 58, identifier:repeat; 59, tuple; 60, identifier:n_f; 61, string:"N/A"; 62, string:"N/A"; 63, string:"N/A"; 64, string:"N/A" | 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; 12, 15; 12, 16; 13, 17; 13, 18; 14, 19; 14, 20; 16, 21; 16, 22; 18, 23; 18, 24; 20, 25; 21, 26; 21, 27; 24, 28; 24, 29; 24, 30; 24, 31; 26, 32; 26, 33; 28, 34; 28, 35; 29, 36; 29, 37; 30, 38; 30, 39; 31, 40; 31, 41; 32, 42; 32, 43; 33, 44; 34, 45; 34, 46; 35, 47; 35, 48; 36, 49; 36, 50; 37, 51; 37, 52; 38, 53; 38, 54; 39, 55; 39, 56; 40, 57; 40, 58; 41, 59; 41, 60; 59, 61; 59, 62; 59, 63; 59, 64 | def describe_features(self, traj):
"""Generic method for describing features.
Parameters
----------
traj : mdtraj.Trajectory
Trajectory to use
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Featurizer name
- featuregroup: Other information
Notes
-------
Method resorts to returning N/A for everything if describe_features in not
implemented in the sub_class
"""
n_f = self.partial_transform(traj).shape[1]
zippy=zip(itertools.repeat("N/A", n_f),
itertools.repeat("N/A", n_f),
itertools.repeat("N/A", n_f),
itertools.repeat(("N/A","N/A","N/A","N/A"), n_f))
return dict_maker(zippy) |
0, module; 1, function_definition; 2, function_name:_mapped_populations; 3, parameters; 4, block; 5, identifier:mdl1; 6, identifier:mdl2; 7, expression_statement; 8, expression_statement; 9, for_statement; 10, return_statement; 11, comment:"""
Method to get the populations for states in mdl 1
from populations inferred in mdl 2. Resorts to 0
if population is not present.
"""; 12, assignment; 13, identifier:i; 14, call; 15, block; 16, identifier:return_vect; 17, identifier:return_vect; 18, call; 19, identifier:range; 20, argument_list; 21, try_statement; 22, attribute; 23, argument_list; 24, attribute; 25, comment:#there has to be a better way to do this; 26, block; 27, except_clause; 28, identifier:np; 29, identifier:zeros; 30, attribute; 31, identifier:mdl1; 32, identifier:n_states_; 33, expression_statement; 34, expression_statement; 35, expression_statement; 36, block; 37, identifier:mdl1; 38, identifier:n_states_; 39, assignment; 40, assignment; 41, assignment; 42, pass_statement; 43, identifier:mdl1_unmapped; 44, subscript; 45, identifier:mdl2_mapped; 46, subscript; 47, subscript; 48, subscript; 49, subscript; 50, integer:0; 51, attribute; 52, identifier:mdl1_unmapped; 53, identifier:return_vect; 54, identifier:i; 55, attribute; 56, identifier:mdl2_mapped; 57, call; 58, integer:0; 59, identifier:mdl2; 60, identifier:mapping_; 61, identifier:mdl2; 62, identifier:populations_; 63, attribute; 64, argument_list; 65, identifier:mdl1; 66, identifier:inverse_transform; 67, list; 68, identifier:i | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 4, 9; 4, 10; 7, 11; 8, 12; 9, 13; 9, 14; 9, 15; 10, 16; 12, 17; 12, 18; 14, 19; 14, 20; 15, 21; 18, 22; 18, 23; 20, 24; 21, 25; 21, 26; 21, 27; 22, 28; 22, 29; 23, 30; 24, 31; 24, 32; 26, 33; 26, 34; 26, 35; 27, 36; 30, 37; 30, 38; 33, 39; 34, 40; 35, 41; 36, 42; 39, 43; 39, 44; 40, 45; 40, 46; 41, 47; 41, 48; 44, 49; 44, 50; 46, 51; 46, 52; 47, 53; 47, 54; 48, 55; 48, 56; 49, 57; 49, 58; 51, 59; 51, 60; 55, 61; 55, 62; 57, 63; 57, 64; 63, 65; 63, 66; 64, 67; 67, 68 | def _mapped_populations(mdl1, mdl2):
"""
Method to get the populations for states in mdl 1
from populations inferred in mdl 2. Resorts to 0
if population is not present.
"""
return_vect = np.zeros(mdl1.n_states_)
for i in range(mdl1.n_states_):
try:
#there has to be a better way to do this
mdl1_unmapped = mdl1.inverse_transform([i])[0][0]
mdl2_mapped = mdl2.mapping_[mdl1_unmapped]
return_vect[i] = mdl2.populations_[mdl2_mapped]
except:
pass
return return_vect |
0, module; 1, function_definition; 2, function_name:query; 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, return_statement; 13, identifier:k; 14, integer:1; 15, identifier:p; 16, integer:2; 17, identifier:distance_upper_bound; 18, attribute; 19, comment:"""Query the kd-tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : int, optional
The number of nearest neighbors to return.
eps : nonnegative float, optional
Return approximate nearest neighbors; the kth returned value
is guaranteed to be no further than (1+eps) times the
distance to the real kth nearest neighbor.
p : float, 1<=p<=infinity, optional
Which Minkowski p-norm to use.
1 is the sum-of-absolute-values "Manhattan" distance
2 is the usual Euclidean distance
infinity is the maximum-coordinate-difference distance
distance_upper_bound : nonnegative float, optional
Return only neighbors within this distance. This is used to prune
tree searches, so if you are doing a series of nearest-neighbor
queries, it may help to supply the distance to the nearest neighbor
of the most recent point.
Returns
-------
d : float or array of floats
The distances to the nearest neighbors.
If x has shape tuple+(self.m,), then d has shape tuple if
k is one, or tuple+(k,) if k is larger than one. Missing
neighbors (e.g. when k > n or distance_upper_bound is
given) are indicated with infinite distances. If k is None,
then d is an object array of shape tuple, containing lists
of distances. In either case the hits are sorted by distance
(nearest first).
i : tuple(int, int) or array of tuple(int, int)
The locations of the neighbors in self.data. Locations are
given by tuples of (traj_i, frame_i)
Examples
--------
>>> from msmbuilder.utils import KDTree
>>> X1 = 0.3 * np.random.RandomState(0).randn(500, 2)
>>> X2 = 0.3 * np.random.RandomState(1).randn(1000, 2) + 10
>>> tree = KDTree([X1, X2])
>>> pts = np.array([[0, 0], [10, 10]])
>>> tree.query(pts)
(array([ 0.0034, 0.0102]), array([[ 0, 410], [ 1, 670]]))
>>> tree.query(pts[0])
(0.0034, array([ 0, 410]))
"""; 20, assignment; 21, expression_list; 22, identifier:np; 23, identifier:inf; 24, pattern_list; 25, call; 26, identifier:cdists; 27, call; 28, identifier:cdists; 29, identifier:cinds; 30, attribute; 31, argument_list; 32, attribute; 33, argument_list; 34, attribute; 35, identifier:query; 36, identifier:x; 37, identifier:k; 38, identifier:p; 39, identifier:distance_upper_bound; 40, identifier:self; 41, identifier:_split_indices; 42, identifier:cinds; 43, identifier:self; 44, identifier:_kdtree | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, 10; 4, 11; 4, 12; 7, 13; 7, 14; 8, 15; 8, 16; 9, 17; 9, 18; 10, 19; 11, 20; 12, 21; 18, 22; 18, 23; 20, 24; 20, 25; 21, 26; 21, 27; 24, 28; 24, 29; 25, 30; 25, 31; 27, 32; 27, 33; 30, 34; 30, 35; 31, 36; 31, 37; 31, 38; 31, 39; 32, 40; 32, 41; 33, 42; 34, 43; 34, 44 | def query(self, x, k=1, p=2, distance_upper_bound=np.inf):
"""Query the kd-tree for nearest neighbors
Parameters
----------
x : array_like, last dimension self.m
An array of points to query.
k : int, optional
The number of nearest neighbors to return.
eps : nonnegative float, optional
Return approximate nearest neighbors; the kth returned value
is guaranteed to be no further than (1+eps) times the
distance to the real kth nearest neighbor.
p : float, 1<=p<=infinity, optional
Which Minkowski p-norm to use.
1 is the sum-of-absolute-values "Manhattan" distance
2 is the usual Euclidean distance
infinity is the maximum-coordinate-difference distance
distance_upper_bound : nonnegative float, optional
Return only neighbors within this distance. This is used to prune
tree searches, so if you are doing a series of nearest-neighbor
queries, it may help to supply the distance to the nearest neighbor
of the most recent point.
Returns
-------
d : float or array of floats
The distances to the nearest neighbors.
If x has shape tuple+(self.m,), then d has shape tuple if
k is one, or tuple+(k,) if k is larger than one. Missing
neighbors (e.g. when k > n or distance_upper_bound is
given) are indicated with infinite distances. If k is None,
then d is an object array of shape tuple, containing lists
of distances. In either case the hits are sorted by distance
(nearest first).
i : tuple(int, int) or array of tuple(int, int)
The locations of the neighbors in self.data. Locations are
given by tuples of (traj_i, frame_i)
Examples
--------
>>> from msmbuilder.utils import KDTree
>>> X1 = 0.3 * np.random.RandomState(0).randn(500, 2)
>>> X2 = 0.3 * np.random.RandomState(1).randn(1000, 2) + 10
>>> tree = KDTree([X1, X2])
>>> pts = np.array([[0, 0], [10, 10]])
>>> tree.query(pts)
(array([ 0.0034, 0.0102]), array([[ 0, 410], [ 1, 670]]))
>>> tree.query(pts[0])
(0.0034, array([ 0, 410]))
"""
cdists, cinds = self._kdtree.query(x, k, p, distance_upper_bound)
return cdists, self._split_indices(cinds) |
0, module; 1, function_definition; 2, function_name:sort_fn_list; 3, parameters; 4, block; 5, identifier:fn_list; 6, expression_statement; 7, expression_statement; 8, expression_statement; 9, return_statement; 10, comment:"""Sort input filename list by datetime
"""; 11, assignment; 12, assignment; 13, identifier:fn_list_sort; 14, identifier:dt_list; 15, call; 16, identifier:fn_list_sort; 17, list_comprehension; 18, identifier:get_dt_list; 19, argument_list; 20, identifier:fn; 21, for_in_clause; 22, identifier:fn_list; 23, tuple_pattern; 24, call; 25, identifier:dt; 26, identifier:fn; 27, identifier:sorted; 28, argument_list; 29, call; 30, identifier:zip; 31, argument_list; 32, identifier:dt_list; 33, identifier:fn_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 8, 12; 9, 13; 11, 14; 11, 15; 12, 16; 12, 17; 15, 18; 15, 19; 17, 20; 17, 21; 19, 22; 21, 23; 21, 24; 23, 25; 23, 26; 24, 27; 24, 28; 28, 29; 29, 30; 29, 31; 31, 32; 31, 33 | def sort_fn_list(fn_list):
"""Sort input filename list by datetime
"""
dt_list = get_dt_list(fn_list)
fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]
return fn_list_sort |
0, module; 1, function_definition; 2, function_name:sort; 3, parameters; 4, block; 5, identifier:iterable; 6, expression_statement; 7, expression_statement; 8, return_statement; 9, comment:"""
Given an IP address list, this function sorts the list.
:type iterable: Iterator
:param iterable: An IP address list.
:rtype: list
:return: The sorted IP address list.
"""; 10, assignment; 11, list_comprehension; 12, identifier:ips; 13, call; 14, call; 15, for_in_clause; 16, identifier:sorted; 17, generator_expression; 18, identifier:clean_ip; 19, argument_list; 20, identifier:ip; 21, identifier:ips; 22, call; 23, for_in_clause; 24, identifier:ip; 25, identifier:normalize_ip; 26, argument_list; 27, identifier:ip; 28, identifier:iterable; 29, identifier:ip | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 6, 9; 7, 10; 8, 11; 10, 12; 10, 13; 11, 14; 11, 15; 13, 16; 13, 17; 14, 18; 14, 19; 15, 20; 15, 21; 17, 22; 17, 23; 19, 24; 22, 25; 22, 26; 23, 27; 23, 28; 26, 29 | def sort(iterable):
"""
Given an IP address list, this function sorts the list.
:type iterable: Iterator
:param iterable: An IP address list.
:rtype: list
:return: The sorted IP address list.
"""
ips = sorted(normalize_ip(ip) for ip in iterable)
return [clean_ip(ip) for ip in ips] |
0, module; 1, function_definition; 2, function_name:glob; 3, parameters; 4, block; 5, identifier:self; 6, expression_statement; 7, expression_statement; 8, comment:# Sort globbed files by tuple (filename, extension); 9, return_statement; 10, comment:"""Returns a sorted glob of files belonging to a given problem"""; 11, assignment; 12, call; 13, identifier:file_glob; 14, call; 15, identifier:sorted; 16, argument_list; 17, attribute; 18, argument_list; 19, identifier:file_glob; 20, keyword_argument; 21, identifier:glob; 22, identifier:glob; 23, call; 24, identifier:key; 25, lambda; 26, attribute; 27, argument_list; 28, lambda_parameters; 29, call; 30, identifier:BASE_NAME; 31, identifier:format; 32, string; 33, attribute; 34, string; 35, string; 36, identifier:f; 37, attribute; 38, argument_list; 39, string_content:*; 40, identifier:self; 41, identifier:num; 42, string_content:*; 43, string_content:.*; 44, attribute; 45, identifier:splitext; 46, identifier:f; 47, identifier:os; 48, identifier:path | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 4, 6; 4, 7; 4, 8; 4, 9; 6, 10; 7, 11; 9, 12; 11, 13; 11, 14; 12, 15; 12, 16; 14, 17; 14, 18; 16, 19; 16, 20; 17, 21; 17, 22; 18, 23; 20, 24; 20, 25; 23, 26; 23, 27; 25, 28; 25, 29; 26, 30; 26, 31; 27, 32; 27, 33; 27, 34; 27, 35; 28, 36; 29, 37; 29, 38; 32, 39; 33, 40; 33, 41; 34, 42; 35, 43; 37, 44; 37, 45; 38, 46; 44, 47; 44, 48 | def glob(self):
"""Returns a sorted glob of files belonging to a given problem"""
file_glob = glob.glob(BASE_NAME.format('*', self.num, '*', '.*'))
# Sort globbed files by tuple (filename, extension)
return sorted(file_glob, key=lambda f: os.path.splitext(f)) |
0, module; 1, function_definition; 2, function_name:event; 3, parameters; 4, block; 5, identifier:self; 6, identifier:interface_id; 7, identifier:address; 8, identifier:value_key; 9, identifier:value; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, if_statement; 14, return_statement; 15, comment:"""If a device emits some sort event, we will handle it here."""; 16, call; 17, call; 18, attribute; 19, block; 20, True; 21, attribute; 22, argument_list; 23, attribute; 24, argument_list; 25, identifier:self; 26, identifier:eventcallback; 27, expression_statement; 28, identifier:LOG; 29, identifier:debug; 30, binary_operator:"RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % (
interface_id, address, value_key.upper(), str(value)); 31, subscript; 32, identifier:event; 33, identifier:interface_id; 34, call; 35, identifier:value; 36, call; 37, string:"RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s"; 38, tuple; 39, subscript; 40, identifier:address; 41, attribute; 42, argument_list; 43, attribute; 44, argument_list; 45, identifier:interface_id; 46, identifier:address; 47, call; 48, call; 49, attribute; 50, subscript; 51, identifier:value_key; 52, identifier:upper; 53, identifier:self; 54, identifier:eventcallback; 55, keyword_argument; 56, keyword_argument; 57, keyword_argument; 58, keyword_argument; 59, attribute; 60, argument_list; 61, identifier:str; 62, argument_list; 63, identifier:self; 64, identifier:devices_all; 65, call; 66, unary_operator; 67, identifier:interface_id; 68, identifier:interface_id; 69, identifier:address; 70, identifier:address; 71, identifier:value_key; 72, call; 73, identifier:value; 74, identifier:value; 75, identifier:value_key; 76, identifier:upper; 77, identifier:value; 78, attribute; 79, argument_list; 80, integer:1; 81, attribute; 82, argument_list; 83, identifier:interface_id; 84, identifier:split; 85, string; 86, identifier:value_key; 87, identifier:upper; 88, string_content:- | 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; 10, 15; 11, 16; 12, 17; 13, 18; 13, 19; 14, 20; 16, 21; 16, 22; 17, 23; 17, 24; 18, 25; 18, 26; 19, 27; 21, 28; 21, 29; 22, 30; 23, 31; 23, 32; 24, 33; 24, 34; 24, 35; 27, 36; 30, 37; 30, 38; 31, 39; 31, 40; 34, 41; 34, 42; 36, 43; 36, 44; 38, 45; 38, 46; 38, 47; 38, 48; 39, 49; 39, 50; 41, 51; 41, 52; 43, 53; 43, 54; 44, 55; 44, 56; 44, 57; 44, 58; 47, 59; 47, 60; 48, 61; 48, 62; 49, 63; 49, 64; 50, 65; 50, 66; 55, 67; 55, 68; 56, 69; 56, 70; 57, 71; 57, 72; 58, 73; 58, 74; 59, 75; 59, 76; 62, 77; 65, 78; 65, 79; 66, 80; 72, 81; 72, 82; 78, 83; 78, 84; 79, 85; 81, 86; 81, 87; 85, 88 | def event(self, interface_id, address, value_key, value):
"""If a device emits some sort event, we will handle it here."""
LOG.debug("RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % (
interface_id, address, value_key.upper(), str(value)))
self.devices_all[interface_id.split(
'-')[-1]][address].event(interface_id, value_key.upper(), value)
if self.eventcallback:
self.eventcallback(interface_id=interface_id, address=address,
value_key=value_key.upper(), value=value)
return True |
0, module; 1, function_definition; 2, function_name:get_isolated_cpus; 3, parameters; 4, block; 5, expression_statement; 6, comment:# The cpu/isolated sysfs was added in Linux 4.2; 7, comment:# (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49); 8, expression_statement; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, if_statement; 13, return_statement; 14, comment:"""Get the list of isolated CPUs.
Return a sorted list of CPU identifiers, or return None if no CPU is
isolated.
"""; 15, assignment; 16, assignment; 17, identifier:isolated; 18, block; 19, assignment; 20, identifier:cmdline; 21, block; 22, None; 23, identifier:path; 24, call; 25, identifier:isolated; 26, call; 27, return_statement; 28, identifier:cmdline; 29, call; 30, expression_statement; 31, if_statement; 32, identifier:sysfs_path; 33, argument_list; 34, identifier:read_first_line; 35, argument_list; 36, call; 37, identifier:read_first_line; 38, argument_list; 39, assignment; 40, identifier:match; 41, block; 42, string; 43, identifier:path; 44, identifier:parse_cpu_list; 45, argument_list; 46, call; 47, identifier:match; 48, call; 49, expression_statement; 50, return_statement; 51, string_content:devices/system/cpu/isolated; 52, identifier:isolated; 53, identifier:proc_path; 54, argument_list; 55, attribute; 56, argument_list; 57, assignment; 58, call; 59, string; 60, identifier:re; 61, identifier:search; 62, string; 63, identifier:cmdline; 64, identifier:isolated; 65, call; 66, identifier:parse_cpu_list; 67, argument_list; 68, string_content:cmdline; 69, string_content:\bisolcpus=([^ ]+); 70, attribute; 71, argument_list; 72, identifier:isolated; 73, identifier:match; 74, identifier:group; 75, integer:1 | 0, 1; 1, 2; 1, 3; 1, 4; 4, 5; 4, 6; 4, 7; 4, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 5, 14; 8, 15; 9, 16; 10, 17; 10, 18; 11, 19; 12, 20; 12, 21; 13, 22; 15, 23; 15, 24; 16, 25; 16, 26; 18, 27; 19, 28; 19, 29; 21, 30; 21, 31; 24, 32; 24, 33; 26, 34; 26, 35; 27, 36; 29, 37; 29, 38; 30, 39; 31, 40; 31, 41; 33, 42; 35, 43; 36, 44; 36, 45; 38, 46; 39, 47; 39, 48; 41, 49; 41, 50; 42, 51; 45, 52; 46, 53; 46, 54; 48, 55; 48, 56; 49, 57; 50, 58; 54, 59; 55, 60; 55, 61; 56, 62; 56, 63; 57, 64; 57, 65; 58, 66; 58, 67; 59, 68; 62, 69; 65, 70; 65, 71; 67, 72; 70, 73; 70, 74; 71, 75 | def get_isolated_cpus():
"""Get the list of isolated CPUs.
Return a sorted list of CPU identifiers, or return None if no CPU is
isolated.
"""
# The cpu/isolated sysfs was added in Linux 4.2
# (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49)
path = sysfs_path('devices/system/cpu/isolated')
isolated = read_first_line(path)
if isolated:
return parse_cpu_list(isolated)
cmdline = read_first_line(proc_path('cmdline'))
if cmdline:
match = re.search(r'\bisolcpus=([^ ]+)', cmdline)
if match:
isolated = match.group(1)
return parse_cpu_list(isolated)
return None |
0, module; 1, function_definition; 2, function_name:framesToFrameRange; 3, parameters; 4, block; 5, identifier:frames; 6, default_parameter; 7, default_parameter; 8, default_parameter; 9, expression_statement; 10, if_statement; 11, expression_statement; 12, if_statement; 13, if_statement; 14, if_statement; 15, return_statement; 16, identifier:sort; 17, True; 18, identifier:zfill; 19, integer:0; 20, identifier:compress; 21, False; 22, comment:"""
Converts an iterator of frames into a
frame range string.
Args:
frames (collections.Iterable): sequence of frames to process
sort (bool): sort the sequence before processing
zfill (int): width for zero padding
compress (bool): remove any duplicates before processing
Returns:
str:
"""; 23, identifier:compress; 24, block; 25, assignment; 26, not_operator; 27, block; 28, comparison_operator:len(frames) == 1; 29, block; 30, identifier:sort; 31, block; 32, call; 33, expression_statement; 34, identifier:frames; 35, call; 36, identifier:frames; 37, return_statement; 38, call; 39, integer:1; 40, return_statement; 41, expression_statement; 42, attribute; 43, argument_list; 44, assignment; 45, identifier:list; 46, argument_list; 47, string; 48, identifier:len; 49, argument_list; 50, call; 51, call; 52, string; 53, identifier:join; 54, call; 55, identifier:frames; 56, call; 57, identifier:frames; 58, identifier:frames; 59, identifier:pad; 60, argument_list; 61, attribute; 62, argument_list; 63, string_content:,; 64, attribute; 65, argument_list; 66, identifier:unique; 67, argument_list; 68, subscript; 69, identifier:zfill; 70, identifier:frames; 71, identifier:sort; 72, identifier:FrameSet; 73, identifier:framesToFrameRanges; 74, identifier:frames; 75, identifier:zfill; 76, call; 77, identifier:frames; 78, identifier:frames; 79, integer:0; 80, identifier:set; 81, argument_list | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, 9; 4, 10; 4, 11; 4, 12; 4, 13; 4, 14; 4, 15; 6, 16; 6, 17; 7, 18; 7, 19; 8, 20; 8, 21; 9, 22; 10, 23; 10, 24; 11, 25; 12, 26; 12, 27; 13, 28; 13, 29; 14, 30; 14, 31; 15, 32; 24, 33; 25, 34; 25, 35; 26, 36; 27, 37; 28, 38; 28, 39; 29, 40; 31, 41; 32, 42; 32, 43; 33, 44; 35, 45; 35, 46; 37, 47; 38, 48; 38, 49; 40, 50; 41, 51; 42, 52; 42, 53; 43, 54; 44, 55; 44, 56; 46, 57; 49, 58; 50, 59; 50, 60; 51, 61; 51, 62; 52, 63; 54, 64; 54, 65; 56, 66; 56, 67; 60, 68; 60, 69; 61, 70; 61, 71; 64, 72; 64, 73; 65, 74; 65, 75; 67, 76; 67, 77; 68, 78; 68, 79; 76, 80; 76, 81 | def framesToFrameRange(frames, sort=True, zfill=0, compress=False):
"""
Converts an iterator of frames into a
frame range string.
Args:
frames (collections.Iterable): sequence of frames to process
sort (bool): sort the sequence before processing
zfill (int): width for zero padding
compress (bool): remove any duplicates before processing
Returns:
str:
"""
if compress:
frames = unique(set(), frames)
frames = list(frames)
if not frames:
return ''
if len(frames) == 1:
return pad(frames[0], zfill)
if sort:
frames.sort()
return ','.join(FrameSet.framesToFrameRanges(frames, zfill)) |
0, module; 1, function_definition; 2, function_name:_normalize_request_parameters; 3, parameters; 4, block; 5, identifier:self; 6, identifier:oauth_params; 7, identifier:req_kwargs; 8, expression_statement; 9, expression_statement; 10, expression_statement; 11, expression_statement; 12, expression_statement; 13, comment:# process request parameters; 14, for_statement; 15, comment:# process request data; 16, if_statement; 17, comment:# extract values from our list of tuples; 18, expression_statement; 19, for_statement; 20, comment:# add in the params from oauth_params for signing; 21, for_statement; 22, comment:# sort the params as per the OAuth 1.0/a spec; 23, expression_statement; 24, comment:# finally encode the params as a string; 25, return_statement; 26, string; 27, assignment; 28, assignment; 29, assignment; 30, assignment; 31, pattern_list; 32, call; 33, block; 34, boolean_operator; 35, block; 36, assignment; 37, identifier:t; 38, identifier:normalized; 39, block; 40, pattern_list; 41, call; 42, block; 43, call; 44, call; 45, string_content:This process normalizes the request parameters as detailed in the OAuth
1.0 spec.
Additionally we apply a `Content-Type` header to the request of the
`FORM_URLENCODE` type if the `Content-Type` was previously set, i.e. if
this is a `POST` or `PUT` request. This ensures the correct header is
set as per spec.
Finally we sort the parameters in preparation for signing and return
a URL encoded string of all normalized parameters.
:param oauth_params: OAuth params to sign with.
:type oauth_params: dict
:param req_kwargs: Request kwargs to normalize.
:type req_kwargs: dict; 46, identifier:normalized; 47, list; 48, identifier:params; 49, call; 50, identifier:data; 51, call; 52, identifier:headers; 53, call; 54, identifier:k; 55, identifier:v; 56, attribute; 57, argument_list; 58, if_statement; 59, comparison_operator:'Content-Type' in headers; 60, line_continuation:\; 61, comparison_operator:headers['Content-Type'] == FORM_URLENCODED; 62, for_statement; 63, identifier:all_normalized; 64, list; 65, expression_statement; 66, if_statement; 67, expression_statement; 68, identifier:k; 69, identifier:v; 70, attribute; 71, argument_list; 72, if_statement; 73, expression_statement; 74, attribute; 75, argument_list; 76, attribute; 77, argument_list; 78, attribute; 79, argument_list; 80, attribute; 81, argument_list; 82, attribute; 83, argument_list; 84, identifier:params; 85, identifier:items; 86, comparison_operator:v is not None; 87, block; 88, string; 89, identifier:headers; 90, subscript; 91, identifier:FORM_URLENCODED; 92, pattern_list; 93, call; 94, block; 95, assignment; 96, boolean_operator; 97, block; 98, augmented_assignment; 99, identifier:oauth_params; 100, identifier:items; 101, comparison_operator:(k, v) in all_normalized; 102, comment:# pragma: no cover; 103, block; 104, augmented_assignment; 105, identifier:all_normalized; 106, identifier:sort; 107, call; 108, line_continuation:\; 109, identifier:replace; 110, string; 111, string; 112, identifier:req_kwargs; 113, identifier:get; 114, string; 115, dictionary; 116, identifier:req_kwargs; 117, identifier:get; 118, string; 119, dictionary; 120, identifier:req_kwargs; 121, identifier:get; 122, string; 123, dictionary; 124, identifier:v; 125, None; 126, expression_statement; 127, string_content:Content-Type; 128, identifier:headers; 129, string; 130, identifier:k; 131, identifier:v; 132, attribute; 133, argument_list; 134, expression_statement; 135, pattern_list; 136, identifier:t; 137, call; 138, not_operator; 139, expression_statement; 140, identifier:all_normalized; 141, list; 142, tuple; 143, identifier:all_normalized; 144, continue_statement; 145, identifier:all_normalized; 146, list; 147, attribute; 148, argument_list; 149, string_content:%7E; 150, string_content:~; 151, string_content:params; 152, string_content:data; 153, string_content:headers; 154, augmented_assignment; 155, string_content:Content-Type; 156, identifier:data; 157, identifier:items; 158, augmented_assignment; 159, identifier:k; 160, identifier:v; 161, identifier:is_basestring; 162, argument_list; 163, call; 164, assignment; 165, tuple; 166, identifier:k; 167, identifier:v; 168, tuple; 169, call; 170, line_continuation:\; 171, identifier:replace; 172, string; 173, string; 174, identifier:normalized; 175, list; 176, identifier:normalized; 177, list; 178, identifier:v; 179, identifier:isinstance; 180, argument_list; 181, identifier:v; 182, call; 183, identifier:k; 184, identifier:v; 185, identifier:k; 186, identifier:v; 187, identifier:urlencode; 188, argument_list; 189, string_content:+; 190, string_content:%20; 191, tuple; 192, tuple; 193, identifier:v; 194, identifier:bytes; 195, attribute; 196, argument_list; 197, identifier:all_normalized; 198, True; 199, identifier:k; 200, identifier:v; 201, identifier:k; 202, identifier:v; 203, identifier:v; 204, identifier:encode; 205, string; 206, string_content:utf-8 | 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; 4, 24; 4, 25; 8, 26; 9, 27; 10, 28; 11, 29; 12, 30; 14, 31; 14, 32; 14, 33; 16, 34; 16, 35; 18, 36; 19, 37; 19, 38; 19, 39; 21, 40; 21, 41; 21, 42; 23, 43; 25, 44; 26, 45; 27, 46; 27, 47; 28, 48; 28, 49; 29, 50; 29, 51; 30, 52; 30, 53; 31, 54; 31, 55; 32, 56; 32, 57; 33, 58; 34, 59; 34, 60; 34, 61; 35, 62; 36, 63; 36, 64; 39, 65; 39, 66; 39, 67; 40, 68; 40, 69; 41, 70; 41, 71; 42, 72; 42, 73; 43, 74; 43, 75; 44, 76; 44, 77; 49, 78; 49, 79; 51, 80; 51, 81; 53, 82; 53, 83; 56, 84; 56, 85; 58, 86; 58, 87; 59, 88; 59, 89; 61, 90; 61, 91; 62, 92; 62, 93; 62, 94; 65, 95; 66, 96; 66, 97; 67, 98; 70, 99; 70, 100; 72, 101; 72, 102; 72, 103; 73, 104; 74, 105; 74, 106; 76, 107; 76, 108; 76, 109; 77, 110; 77, 111; 78, 112; 78, 113; 79, 114; 79, 115; 80, 116; 80, 117; 81, 118; 81, 119; 82, 120; 82, 121; 83, 122; 83, 123; 86, 124; 86, 125; 87, 126; 88, 127; 90, 128; 90, 129; 92, 130; 92, 131; 93, 132; 93, 133; 94, 134; 95, 135; 95, 136; 96, 137; 96, 138; 97, 139; 98, 140; 98, 141; 101, 142; 101, 143; 103, 144; 104, 145; 104, 146; 107, 147; 107, 148; 110, 149; 111, 150; 114, 151; 118, 152; 122, 153; 126, 154; 129, 155; 132, 156; 132, 157; 134, 158; 135, 159; 135, 160; 137, 161; 137, 162; 138, 163; 139, 164; 141, 165; 142, 166; 142, 167; 146, 168; 147, 169; 147, 170; 147, 171; 148, 172; 148, 173; 154, 174; 154, 175; 158, 176; 158, 177; 162, 178; 163, 179; 163, 180; 164, 181; 164, 182; 165, 183; 165, 184; 168, 185; 168, 186; 169, 187; 169, 188; 172, 189; 173, 190; 175, 191; 177, 192; 180, 193; 180, 194; 182, 195; 182, 196; 188, 197; 188, 198; 191, 199; 191, 200; 192, 201; 192, 202; 195, 203; 195, 204; 196, 205; 205, 206 | def _normalize_request_parameters(self, oauth_params, req_kwargs):
'''
This process normalizes the request parameters as detailed in the OAuth
1.0 spec.
Additionally we apply a `Content-Type` header to the request of the
`FORM_URLENCODE` type if the `Content-Type` was previously set, i.e. if
this is a `POST` or `PUT` request. This ensures the correct header is
set as per spec.
Finally we sort the parameters in preparation for signing and return
a URL encoded string of all normalized parameters.
:param oauth_params: OAuth params to sign with.
:type oauth_params: dict
:param req_kwargs: Request kwargs to normalize.
:type req_kwargs: dict
'''
normalized = []
params = req_kwargs.get('params', {})
data = req_kwargs.get('data', {})
headers = req_kwargs.get('headers', {})
# process request parameters
for k, v in params.items():
if v is not None:
normalized += [(k, v)]
# process request data
if 'Content-Type' in headers and \
headers['Content-Type'] == FORM_URLENCODED:
for k, v in data.items():
normalized += [(k, v)]
# extract values from our list of tuples
all_normalized = []
for t in normalized:
k, v = t
if is_basestring(v) and not isinstance(v, bytes):
v = v.encode('utf-8')
all_normalized += [(k, v)]
# add in the params from oauth_params for signing
for k, v in oauth_params.items():
if (k, v) in all_normalized: # pragma: no cover
continue
all_normalized += [(k, v)]
# sort the params as per the OAuth 1.0/a spec
all_normalized.sort()
# finally encode the params as a string
return urlencode(all_normalized, True)\
.replace('+', '%20')\
.replace('%7E', '~') |
0, module; 1, function_definition; 2, function_name:do_summary; 3, parameters; 4, block; 5, identifier:self; 6, identifier:params; 7, expression_statement; 8, expression_statement; 9, expression_statement; 10, comment:# what slice do we want?; 11, if_statement; 12, expression_statement; 13, for_statement; 14, comment:"""
\x1b[1mNAME\x1b[0m
summary - Prints summarized details of a path's children
\x1b[1mSYNOPSIS\x1b[0m
summary [path] [top]
\x1b[1mDESCRIPTION\x1b[0m
The results are sorted by name.
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* top: number of results to be displayed (0 is all) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> summary /services/registrations
Created Last modified Owner Name
Thu Oct 11 09:14:39 2014 Thu Oct 11 09:14:39 2014 - bar
Thu Oct 16 18:54:39 2014 Thu Oct 16 18:54:39 2014 - foo
Thu Oct 12 10:04:01 2014 Thu Oct 12 10:04:01 2014 0x14911e869aa0dc1 member_0000001
"""; 15, call; 16, assignment; 17, comparison_operator:params.top == 0; 18, block; 19, elif_clause; 20, else_clause; 21, assignment; 22, identifier:i; 23, call; 24, block; 25, attribute; 26, argument_list; 27, identifier:results; 28, call; 29, attribute; 30, integer:0; 31, expression_statement; 32, comparison_operator:params.top > 0; 33, block; 34, block; 35, identifier:offs; 36, conditional_expression:1 if params.path == "/" else len(params.path) + 1; 37, identifier:range; 38, argument_list; 39, expression_statement; 40, expression_statement; 41, identifier:self; 42, identifier:show_output; 43, string:"%s%s%s%s"; 44, call; 45, call; 46, call; 47, string:"Name"; 48, identifier:sorted; 49, argument_list; 50, identifier:params; 51, identifier:top; 52, assignment; 53, attribute; 54, integer:0; 55, expression_statement; 56, expression_statement; 57, expression_statement; 58, integer:1; 59, comparison_operator:params.path == "/"; 60, binary_operator:len(params.path) + 1; 61, identifier:start; 62, identifier:end; 63, assignment; 64, call; 65, attribute; 66, argument_list; 67, attribute; 68, argument_list; 69, attribute; 70, argument_list; 71, call; 72, pattern_list; 73, expression_list; 74, identifier:params; 75, identifier:top; 76, assignment; 77, assignment; 78, assignment; 79, attribute; 80, string:"/"; 81, call; 82, integer:1; 83, pattern_list; 84, subscript; 85, attribute; 86, argument_list; 87, string:"Created"; 88, identifier:ljust; 89, integer:32; 90, string:"Last modified"; 91, identifier:ljust; 92, integer:32; 93, string:"Owner"; 94, identifier:ljust; 95, integer:23; 96, attribute; 97, argument_list; 98, identifier:start; 99, identifier:end; 100, integer:0; 101, call; 102, pattern_list; 103, expression_list; 104, identifier:start; 105, conditional_expression:len(results) + params.top if abs(params.top) < len(results) else 0; 106, identifier:end; 107, call; 108, identifier:params; 109, identifier:path; 110, identifier:len; 111, argument_list; 112, identifier:path; 113, identifier:stat; 114, identifier:results; 115, identifier:i; 116, identifier:self; 117, identifier:show_output; 118, string:"%s%s%s%s"; 119, call; 120, call; 121, call; 122, subscript; 123, attribute; 124, identifier:stat_map; 125, attribute; 126, identifier:len; 127, argument_list; 128, identifier:start; 129, identifier:end; 130, integer:0; 131, conditional_expression:params.top if params.top < len(results) else len(results); 132, binary_operator:len(results) + params.top; 133, comparison_operator:abs(params.top) < len(results); 134, integer:0; 135, identifier:len; 136, argument_list; 137, attribute; 138, attribute; 139, argument_list; 140, attribute; 141, argument_list; 142, attribute; 143, argument_list; 144, identifier:path; 145, slice; 146, identifier:self; 147, identifier:_zk; 148, identifier:params; 149, identifier:path; 150, identifier:results; 151, attribute; 152, comparison_operator:params.top < len(results); 153, call; 154, call; 155, attribute; 156, call; 157, call; 158, identifier:results; 159, identifier:params; 160, identifier:path; 161, call; 162, identifier:ljust; 163, integer:32; 164, call; 165, identifier:ljust; 166, integer:32; 167, parenthesized_expression; 168, identifier:ljust; 169, integer:23; 170, identifier:offs; 171, identifier:params; 172, identifier:top; 173, attribute; 174, call; 175, identifier:len; 176, argument_list; 177, identifier:len; 178, argument_list; 179, identifier:params; 180, identifier:top; 181, identifier:abs; 182, argument_list; 183, identifier:len; 184, argument_list; 185, attribute; 186, argument_list; 187, attribute; 188, argument_list; 189, binary_operator:"0x%x" % stat.ephemeralOwner; 190, identifier:params; 191, identifier:top; 192, identifier:len; 193, argument_list; 194, identifier:results; 195, identifier:results; 196, attribute; 197, identifier:results; 198, identifier:time; 199, identifier:ctime; 200, attribute; 201, identifier:time; 202, identifier:ctime; 203, attribute; 204, string:"0x%x"; 205, attribute; 206, identifier:results; 207, identifier:params; 208, identifier:top; 209, identifier:stat; 210, identifier:created; 211, identifier:stat; 212, identifier:last_modified; 213, identifier:stat; 214, identifier:ephemeralOwner | 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; 11, 17; 11, 18; 11, 19; 11, 20; 12, 21; 13, 22; 13, 23; 13, 24; 15, 25; 15, 26; 16, 27; 16, 28; 17, 29; 17, 30; 18, 31; 19, 32; 19, 33; 20, 34; 21, 35; 21, 36; 23, 37; 23, 38; 24, 39; 24, 40; 25, 41; 25, 42; 26, 43; 26, 44; 26, 45; 26, 46; 26, 47; 28, 48; 28, 49; 29, 50; 29, 51; 31, 52; 32, 53; 32, 54; 33, 55; 34, 56; 34, 57; 36, 58; 36, 59; 36, 60; 38, 61; 38, 62; 39, 63; 40, 64; 44, 65; 44, 66; 45, 67; 45, 68; 46, 69; 46, 70; 49, 71; 52, 72; 52, 73; 53, 74; 53, 75; 55, 76; 56, 77; 57, 78; 59, 79; 59, 80; 60, 81; 60, 82; 63, 83; 63, 84; 64, 85; 64, 86; 65, 87; 65, 88; 66, 89; 67, 90; 67, 91; 68, 92; 69, 93; 69, 94; 70, 95; 71, 96; 71, 97; 72, 98; 72, 99; 73, 100; 73, 101; 76, 102; 76, 103; 77, 104; 77, 105; 78, 106; 78, 107; 79, 108; 79, 109; 81, 110; 81, 111; 83, 112; 83, 113; 84, 114; 84, 115; 85, 116; 85, 117; 86, 118; 86, 119; 86, 120; 86, 121; 86, 122; 96, 123; 96, 124; 97, 125; 101, 126; 101, 127; 102, 128; 102, 129; 103, 130; 103, 131; 105, 132; 105, 133; 105, 134; 107, 135; 107, 136; 111, 137; 119, 138; 119, 139; 120, 140; 120, 141; 121, 142; 121, 143; 122, 144; 122, 145; 123, 146; 123, 147; 125, 148; 125, 149; 127, 150; 131, 151; 131, 152; 131, 153; 132, 154; 132, 155; 133, 156; 133, 157; 136, 158; 137, 159; 137, 160; 138, 161; 138, 162; 139, 163; 140, 164; 140, 165; 141, 166; 142, 167; 142, 168; 143, 169; 145, 170; 151, 171; 151, 172; 152, 173; 152, 174; 153, 175; 153, 176; 154, 177; 154, 178; 155, 179; 155, 180; 156, 181; 156, 182; 157, 183; 157, 184; 161, 185; 161, 186; 164, 187; 164, 188; 167, 189; 173, 190; 173, 191; 174, 192; 174, 193; 176, 194; 178, 195; 182, 196; 184, 197; 185, 198; 185, 199; 186, 200; 187, 201; 187, 202; 188, 203; 189, 204; 189, 205; 193, 206; 196, 207; 196, 208; 200, 209; 200, 210; 203, 211; 203, 212; 205, 213; 205, 214 | def do_summary(self, params):
"""
\x1b[1mNAME\x1b[0m
summary - Prints summarized details of a path's children
\x1b[1mSYNOPSIS\x1b[0m
summary [path] [top]
\x1b[1mDESCRIPTION\x1b[0m
The results are sorted by name.
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* top: number of results to be displayed (0 is all) (default: 0)
\x1b[1mEXAMPLES\x1b[0m
> summary /services/registrations
Created Last modified Owner Name
Thu Oct 11 09:14:39 2014 Thu Oct 11 09:14:39 2014 - bar
Thu Oct 16 18:54:39 2014 Thu Oct 16 18:54:39 2014 - foo
Thu Oct 12 10:04:01 2014 Thu Oct 12 10:04:01 2014 0x14911e869aa0dc1 member_0000001
"""
self.show_output("%s%s%s%s",
"Created".ljust(32),
"Last modified".ljust(32),
"Owner".ljust(23),
"Name")
results = sorted(self._zk.stat_map(params.path))
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
offs = 1 if params.path == "/" else len(params.path) + 1
for i in range(start, end):
path, stat = results[i]
self.show_output(
"%s%s%s%s",
time.ctime(stat.created).ljust(32),
time.ctime(stat.last_modified).ljust(32),
("0x%x" % stat.ephemeralOwner).ljust(23),
path[offs:]
) |
0, module; 1, function_definition; 2, function_name:do_json_count_values; 3, parameters; 4, block; 5, identifier:self; 6, identifier:params; 7, expression_statement; 8, try_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, expression_statement; 13, expression_statement; 14, comment:# what slice do we want?; 15, if_statement; 16, if_statement; 17, for_statement; 18, comment:# if no results were found we call it a failure (i.e.: exit(1) from --run-once); 19, if_statement; 20, comment:"""
\x1b[1mNAME\x1b[0m
json_count_values - Gets the frequency of the values associated with the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_count_values <path> <keys> [top] [minfreq] [reverse] [report_errors] [print_path]
\x1b[1mOPTIONS\x1b[0m
* top: number of results to show (0 is all) (default: 0)
* minfreq: minimum frequency to be displayed (default: 1)
* reverse: sort in descending order (default: true)
* report_errors: report bad znodes (default: false)
* print_path: print the path if there are results (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_count_values /configs/primary_service endpoint.host
10.20.0.2 3
10.20.0.4 3
10.20.0.5 3
10.20.0.6 1
10.20.0.7 1
...
"""; 21, block; 22, except_clause; 23, assignment; 24, assignment; 25, pattern_list; 26, call; 27, block; 28, assignment; 29, assignment; 30, comparison_operator:params.top == 0; 31, block; 32, elif_clause; 33, else_clause; 34, boolean_operator; 35, block; 36, identifier:i; 37, call; 38, block; 39, comparison_operator:len(results) == 0; 40, block; 41, expression_statement; 42, as_pattern; 43, block; 44, identifier:path_map; 45, call; 46, identifier:values; 47, call; 48, identifier:path; 49, identifier:data; 50, attribute; 51, argument_list; 52, try_statement; 53, identifier:results; 54, call; 55, identifier:results; 56, list_comprehension; 57, attribute; 58, integer:0; 59, expression_statement; 60, comparison_operator:params.top > 0; 61, block; 62, block; 63, comparison_operator:len(results) > 0; 64, attribute; 65, expression_statement; 66, identifier:range; 67, argument_list; 68, expression_statement; 69, expression_statement; 70, call; 71, integer:0; 72, return_statement; 73, call; 74, attribute; 75, as_pattern_target; 76, expression_statement; 77, return_statement; 78, identifier:PathMap; 79, argument_list; 80, identifier:defaultdict; 81, argument_list; 82, identifier:path_map; 83, identifier:get; 84, block; 85, except_clause; 86, except_clause; 87, identifier:sorted; 88, argument_list; 89, identifier:r; 90, for_in_clause; 91, if_clause; 92, identifier:params; 93, identifier:top; 94, assignment; 95, attribute; 96, integer:0; 97, expression_statement; 98, expression_statement; 99, expression_statement; 100, call; 101, integer:0; 102, identifier:params; 103, identifier:print_path; 104, call; 105, identifier:start; 106, identifier:end; 107, assignment; 108, call; 109, identifier:len; 110, argument_list; 111, False; 112, attribute; 113, argument_list; 114, identifier:Keys; 115, identifier:Bad; 116, identifier:ex; 117, call; 118, attribute; 119, attribute; 120, identifier:int; 121, expression_statement; 122, expression_statement; 123, as_pattern; 124, block; 125, as_pattern; 126, block; 127, call; 128, keyword_argument; 129, keyword_argument; 130, identifier:r; 131, identifier:results; 132, comparison_operator:r[1] >= params.minfreq; 133, pattern_list; 134, expression_list; 135, identifier:params; 136, identifier:top; 137, assignment; 138, assignment; 139, assignment; 140, identifier:len; 141, argument_list; 142, attribute; 143, argument_list; 144, pattern_list; 145, subscript; 146, attribute; 147, argument_list; 148, identifier:results; 149, identifier:Keys; 150, identifier:validate; 151, attribute; 152, attribute; 153, argument_list; 154, identifier:self; 155, identifier:_zk; 156, identifier:params; 157, identifier:path; 158, assignment; 159, augmented_assignment; 160, identifier:BadJSON; 161, as_pattern_target; 162, if_statement; 163, attribute; 164, as_pattern_target; 165, if_statement; 166, attribute; 167, argument_list; 168, identifier:key; 169, lambda; 170, identifier:reverse; 171, attribute; 172, subscript; 173, attribute; 174, identifier:start; 175, identifier:end; 176, integer:0; 177, call; 178, pattern_list; 179, expression_list; 180, identifier:start; 181, conditional_expression:len(results) + params.top if abs(params.top) < len(results) else 0; 182, identifier:end; 183, call; 184, identifier:results; 185, identifier:self; 186, identifier:show_output; 187, attribute; 188, identifier:value; 189, identifier:frequency; 190, identifier:results; 191, identifier:i; 192, identifier:self; 193, identifier:show_output; 194, string:"%s = %d"; 195, identifier:value; 196, identifier:frequency; 197, identifier:params; 198, identifier:keys; 199, identifier:self; 200, identifier:show_output; 201, call; 202, identifier:value; 203, call; 204, subscript; 205, integer:1; 206, identifier:ex; 207, attribute; 208, block; 209, identifier:Keys; 210, identifier:Missing; 211, identifier:ex; 212, attribute; 213, block; 214, identifier:values; 215, identifier:items; 216, lambda_parameters; 217, subscript; 218, identifier:params; 219, identifier:reverse; 220, identifier:r; 221, integer:1; 222, identifier:params; 223, identifier:minfreq; 224, identifier:len; 225, argument_list; 226, identifier:start; 227, identifier:end; 228, integer:0; 229, conditional_expression:params.top if params.top < len(results) else len(results); 230, binary_operator:len(results) + params.top; 231, comparison_operator:abs(params.top) < len(results); 232, integer:0; 233, identifier:len; 234, argument_list; 235, identifier:params; 236, identifier:path; 237, identifier:str; 238, argument_list; 239, attribute; 240, argument_list; 241, identifier:values; 242, identifier:value; 243, identifier:params; 244, identifier:report_errors; 245, expression_statement; 246, identifier:params; 247, identifier:report_errors; 248, expression_statement; 249, identifier:item; 250, identifier:item; 251, integer:1; 252, identifier:results; 253, attribute; 254, comparison_operator:params.top < len(results); 255, call; 256, call; 257, attribute; 258, call; 259, call; 260, identifier:results; 261, identifier:ex; 262, identifier:Keys; 263, identifier:value; 264, call; 265, attribute; 266, call; 267, call; 268, identifier:params; 269, identifier:top; 270, attribute; 271, call; 272, identifier:len; 273, argument_list; 274, identifier:len; 275, argument_list; 276, identifier:params; 277, identifier:top; 278, identifier:abs; 279, argument_list; 280, identifier:len; 281, argument_list; 282, identifier:json_deserialize; 283, argument_list; 284, identifier:params; 285, identifier:keys; 286, attribute; 287, argument_list; 288, attribute; 289, argument_list; 290, identifier:params; 291, identifier:top; 292, identifier:len; 293, argument_list; 294, identifier:results; 295, identifier:results; 296, attribute; 297, identifier:results; 298, identifier:data; 299, identifier:self; 300, identifier:show_output; 301, string:"Path %s has bad JSON."; 302, identifier:path; 303, identifier:self; 304, identifier:show_output; 305, string:"Path %s is missing key %s."; 306, identifier:path; 307, identifier:ex; 308, identifier:results; 309, identifier:params; 310, identifier:top | 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; 7, 20; 8, 21; 8, 22; 9, 23; 10, 24; 11, 25; 11, 26; 11, 27; 12, 28; 13, 29; 15, 30; 15, 31; 15, 32; 15, 33; 16, 34; 16, 35; 17, 36; 17, 37; 17, 38; 19, 39; 19, 40; 21, 41; 22, 42; 22, 43; 23, 44; 23, 45; 24, 46; 24, 47; 25, 48; 25, 49; 26, 50; 26, 51; 27, 52; 28, 53; 28, 54; 29, 55; 29, 56; 30, 57; 30, 58; 31, 59; 32, 60; 32, 61; 33, 62; 34, 63; 34, 64; 35, 65; 37, 66; 37, 67; 38, 68; 38, 69; 39, 70; 39, 71; 40, 72; 41, 73; 42, 74; 42, 75; 43, 76; 43, 77; 45, 78; 45, 79; 47, 80; 47, 81; 50, 82; 50, 83; 52, 84; 52, 85; 52, 86; 54, 87; 54, 88; 56, 89; 56, 90; 56, 91; 57, 92; 57, 93; 59, 94; 60, 95; 60, 96; 61, 97; 62, 98; 62, 99; 63, 100; 63, 101; 64, 102; 64, 103; 65, 104; 67, 105; 67, 106; 68, 107; 69, 108; 70, 109; 70, 110; 72, 111; 73, 112; 73, 113; 74, 114; 74, 115; 75, 116; 76, 117; 79, 118; 79, 119; 81, 120; 84, 121; 84, 122; 85, 123; 85, 124; 86, 125; 86, 126; 88, 127; 88, 128; 88, 129; 90, 130; 90, 131; 91, 132; 94, 133; 94, 134; 95, 135; 95, 136; 97, 137; 98, 138; 99, 139; 100, 140; 100, 141; 104, 142; 104, 143; 107, 144; 107, 145; 108, 146; 108, 147; 110, 148; 112, 149; 112, 150; 113, 151; 117, 152; 117, 153; 118, 154; 118, 155; 119, 156; 119, 157; 121, 158; 122, 159; 123, 160; 123, 161; 124, 162; 125, 163; 125, 164; 126, 165; 127, 166; 127, 167; 128, 168; 128, 169; 129, 170; 129, 171; 132, 172; 132, 173; 133, 174; 133, 175; 134, 176; 134, 177; 137, 178; 137, 179; 138, 180; 138, 181; 139, 182; 139, 183; 141, 184; 142, 185; 142, 186; 143, 187; 144, 188; 144, 189; 145, 190; 145, 191; 146, 192; 146, 193; 147, 194; 147, 195; 147, 196; 151, 197; 151, 198; 152, 199; 152, 200; 153, 201; 158, 202; 158, 203; 159, 204; 159, 205; 161, 206; 162, 207; 162, 208; 163, 209; 163, 210; 164, 211; 165, 212; 165, 213; 166, 214; 166, 215; 169, 216; 169, 217; 171, 218; 171, 219; 172, 220; 172, 221; 173, 222; 173, 223; 177, 224; 177, 225; 178, 226; 178, 227; 179, 228; 179, 229; 181, 230; 181, 231; 181, 232; 183, 233; 183, 234; 187, 235; 187, 236; 201, 237; 201, 238; 203, 239; 203, 240; 204, 241; 204, 242; 207, 243; 207, 244; 208, 245; 212, 246; 212, 247; 213, 248; 216, 249; 217, 250; 217, 251; 225, 252; 229, 253; 229, 254; 229, 255; 230, 256; 230, 257; 231, 258; 231, 259; 234, 260; 238, 261; 239, 262; 239, 263; 240, 264; 240, 265; 245, 266; 248, 267; 253, 268; 253, 269; 254, 270; 254, 271; 255, 272; 255, 273; 256, 274; 256, 275; 257, 276; 257, 277; 258, 278; 258, 279; 259, 280; 259, 281; 264, 282; 264, 283; 265, 284; 265, 285; 266, 286; 266, 287; 267, 288; 267, 289; 270, 290; 270, 291; 271, 292; 271, 293; 273, 294; 275, 295; 279, 296; 281, 297; 283, 298; 286, 299; 286, 300; 287, 301; 287, 302; 288, 303; 288, 304; 289, 305; 289, 306; 289, 307; 293, 308; 296, 309; 296, 310 | def do_json_count_values(self, params):
"""
\x1b[1mNAME\x1b[0m
json_count_values - Gets the frequency of the values associated with the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_count_values <path> <keys> [top] [minfreq] [reverse] [report_errors] [print_path]
\x1b[1mOPTIONS\x1b[0m
* top: number of results to show (0 is all) (default: 0)
* minfreq: minimum frequency to be displayed (default: 1)
* reverse: sort in descending order (default: true)
* report_errors: report bad znodes (default: false)
* print_path: print the path if there are results (default: false)
\x1b[1mEXAMPLES\x1b[0m
> json_count_values /configs/primary_service endpoint.host
10.20.0.2 3
10.20.0.4 3
10.20.0.5 3
10.20.0.6 1
10.20.0.7 1
...
"""
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
values = defaultdict(int)
for path, data in path_map.get():
try:
value = Keys.value(json_deserialize(data), params.keys)
values[value] += 1
except BadJSON as ex:
if params.report_errors:
self.show_output("Path %s has bad JSON.", path)
except Keys.Missing as ex:
if params.report_errors:
self.show_output("Path %s is missing key %s.", path, ex)
results = sorted(values.items(), key=lambda item: item[1], reverse=params.reverse)
results = [r for r in results if r[1] >= params.minfreq]
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
if len(results) > 0 and params.print_path:
self.show_output(params.path)
for i in range(start, end):
value, frequency = results[i]
self.show_output("%s = %d", value, frequency)
# if no results were found we call it a failure (i.e.: exit(1) from --run-once)
if len(results) == 0:
return False |
0, module; 1, function_definition; 2, function_name:do_json_dupes_for_keys; 3, parameters; 4, block; 5, identifier:self; 6, identifier:params; 7, expression_statement; 8, try_statement; 9, expression_statement; 10, expression_statement; 11, for_statement; 12, expression_statement; 13, for_statement; 14, for_statement; 15, comment:# if no dupes were found we call it a failure (i.e.: exit(1) from --run-once); 16, if_statement; 17, comment:"""
\x1b[1mNAME\x1b[0m
json_duples_for_keys - Gets the duplicate znodes for the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_dupes_for_keys <path> <keys> [prefix] [report_errors] [first]
\x1b[1mDESCRIPTION\x1b[0m
Znodes with duplicated keys are sorted and all but the first (original) one
are printed.
\x1b[1mOPTIONS\x1b[0m
* prefix: only include matching znodes
* report_errors: turn on error reporting (i.e.: bad JSON in a znode)
* first: print the first, non duplicated, znode too.
\x1b[1mEXAMPLES\x1b[0m
> json_cat /configs/primary_service true
member_0000000186
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
member_0000000187
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
> json_dupes_for_keys /configs/primary_service shard
member_0000000187
"""; 18, block; 19, except_clause; 20, assignment; 21, assignment; 22, pattern_list; 23, call; 24, block; 25, assignment; 26, pattern_list; 27, call; 28, block; 29, identifier:dup; 30, identifier:dupes; 31, block; 32, comparison_operator:len(dupes) == 0; 33, block; 34, expression_statement; 35, as_pattern; 36, block; 37, identifier:path_map; 38, call; 39, identifier:dupes_by_path; 40, call; 41, identifier:path; 42, identifier:data; 43, attribute; 44, argument_list; 45, expression_statement; 46, if_statement; 47, try_statement; 48, identifier:dupes; 49, list; 50, identifier:_; 51, identifier:paths_by_value; 52, attribute; 53, argument_list; 54, for_statement; 55, expression_statement; 56, call; 57, integer:0; 58, return_statement; 59, call; 60, attribute; 61, as_pattern_target; 62, expression_statement; 63, return_statement; 64, identifier:PathMap; 65, argument_list; 66, identifier:defaultdict; 67, argument_list; 68, identifier:path_map; 69, identifier:get; 70, assignment; 71, not_operator; 72, block; 73, block; 74, except_clause; 75, except_clause; 76, identifier:dupes_by_path; 77, identifier:items; 78, pattern_list; 79, call; 80, block; 81, call; 82, identifier:len; 83, argument_list; 84, False; 85, attribute; 86, argument_list; 87, identifier:Keys; 88, identifier:Bad; 89, identifier:ex; 90, call; 91, attribute; 92, attribute; 93, lambda; 94, pattern_list; 95, call; 96, call; 97, continue_statement; 98, expression_statement; 99, expression_statement; 100, as_pattern; 101, block; 102, as_pattern; 103, block; 104, identifier:_; 105, identifier:paths; 106, attribute; 107, argument_list; 108, if_statement; 109, attribute; 110, argument_list; 111, identifier:dupes; 112, identifier:Keys; 113, identifier:validate; 114, attribute; 115, attribute; 116, argument_list; 117, identifier:self; 118, identifier:_zk; 119, identifier:params; 120, identifier:path; 121, call; 122, identifier:parent; 123, identifier:child; 124, identifier:split; 125, argument_list; 126, attribute; 127, argument_list; 128, assignment; 129, call; 130, identifier:BadJSON; 131, as_pattern_target; 132, if_statement; 133, attribute; 134, as_pattern_target; 135, if_statement; 136, identifier:paths_by_value; 137, identifier:items; 138, comparison_operator:len(paths) > 1; 139, block; 140, identifier:self; 141, identifier:show_output; 142, identifier:dup; 143, identifier:params; 144, identifier:keys; 145, identifier:self; 146, identifier:show_output; 147, call; 148, identifier:defaultdict; 149, argument_list; 150, identifier:path; 151, identifier:child; 152, identifier:startswith; 153, attribute; 154, identifier:value; 155, call; 156, attribute; 157, argument_list; 158, identifier:ex; 159, attribute; 160, block; 161, identifier:Keys; 162, identifier:Missing; 163, identifier:ex; 164, attribute; 165, block; 166, call; 167, integer:1; 168, expression_statement; 169, expression_statement; 170, for_statement; 171, identifier:str; 172, argument_list; 173, identifier:list; 174, identifier:params; 175, identifier:prefix; 176, attribute; 177, argument_list; 178, subscript; 179, identifier:append; 180, identifier:path; 181, identifier:params; 182, identifier:report_errors; 183, expression_statement; 184, identifier:params; 185, identifier:report_errors; 186, expression_statement; 187, identifier:len; 188, argument_list; 189, call; 190, assignment; 191, identifier:path; 192, identifier:paths; 193, block; 194, identifier:ex; 195, identifier:Keys; 196, identifier:value; 197, call; 198, attribute; 199, subscript; 200, identifier:value; 201, call; 202, call; 203, identifier:paths; 204, attribute; 205, argument_list; 206, identifier:paths; 207, conditional_expression:paths if params.first else paths[1:]; 208, expression_statement; 209, expression_statement; 210, identifier:json_deserialize; 211, argument_list; 212, identifier:params; 213, identifier:keys; 214, identifier:dupes_by_path; 215, identifier:parent; 216, attribute; 217, argument_list; 218, attribute; 219, argument_list; 220, identifier:paths; 221, identifier:sort; 222, identifier:paths; 223, attribute; 224, subscript; 225, assignment; 226, call; 227, identifier:data; 228, identifier:self; 229, identifier:show_output; 230, string:"Path %s has bad JSON."; 231, identifier:path; 232, identifier:self; 233, identifier:show_output; 234, string:"Path %s is missing key %s."; 235, identifier:path; 236, identifier:ex; 237, identifier:params; 238, identifier:first; 239, identifier:paths; 240, slice; 241, identifier:idx; 242, call; 243, attribute; 244, argument_list; 245, integer:1; 246, attribute; 247, argument_list; 248, identifier:dupes; 249, identifier:insert; 250, identifier:idx; 251, identifier:path; 252, identifier:bisect; 253, identifier:bisect; 254, identifier:dupes; 255, identifier:path | 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; 8, 19; 9, 20; 10, 21; 11, 22; 11, 23; 11, 24; 12, 25; 13, 26; 13, 27; 13, 28; 14, 29; 14, 30; 14, 31; 16, 32; 16, 33; 18, 34; 19, 35; 19, 36; 20, 37; 20, 38; 21, 39; 21, 40; 22, 41; 22, 42; 23, 43; 23, 44; 24, 45; 24, 46; 24, 47; 25, 48; 25, 49; 26, 50; 26, 51; 27, 52; 27, 53; 28, 54; 31, 55; 32, 56; 32, 57; 33, 58; 34, 59; 35, 60; 35, 61; 36, 62; 36, 63; 38, 64; 38, 65; 40, 66; 40, 67; 43, 68; 43, 69; 45, 70; 46, 71; 46, 72; 47, 73; 47, 74; 47, 75; 52, 76; 52, 77; 54, 78; 54, 79; 54, 80; 55, 81; 56, 82; 56, 83; 58, 84; 59, 85; 59, 86; 60, 87; 60, 88; 61, 89; 62, 90; 65, 91; 65, 92; 67, 93; 70, 94; 70, 95; 71, 96; 72, 97; 73, 98; 73, 99; 74, 100; 74, 101; 75, 102; 75, 103; 78, 104; 78, 105; 79, 106; 79, 107; 80, 108; 81, 109; 81, 110; 83, 111; 85, 112; 85, 113; 86, 114; 90, 115; 90, 116; 91, 117; 91, 118; 92, 119; 92, 120; 93, 121; 94, 122; 94, 123; 95, 124; 95, 125; 96, 126; 96, 127; 98, 128; 99, 129; 100, 130; 100, 131; 101, 132; 102, 133; 102, 134; 103, 135; 106, 136; 106, 137; 108, 138; 108, 139; 109, 140; 109, 141; 110, 142; 114, 143; 114, 144; 115, 145; 115, 146; 116, 147; 121, 148; 121, 149; 125, 150; 126, 151; 126, 152; 127, 153; 128, 154; 128, 155; 129, 156; 129, 157; 131, 158; 132, 159; 132, 160; 133, 161; 133, 162; 134, 163; 135, 164; 135, 165; 138, 166; 138, 167; 139, 168; 139, 169; 139, 170; 147, 171; 147, 172; 149, 173; 153, 174; 153, 175; 155, 176; 155, 177; 156, 178; 156, 179; 157, 180; 159, 181; 159, 182; 160, 183; 164, 184; 164, 185; 165, 186; 166, 187; 166, 188; 168, 189; 169, 190; 170, 191; 170, 192; 170, 193; 172, 194; 176, 195; 176, 196; 177, 197; 177, 198; 178, 199; 178, 200; 183, 201; 186, 202; 188, 203; 189, 204; 189, 205; 190, 206; 190, 207; 193, 208; 193, 209; 197, 210; 197, 211; 198, 212; 198, 213; 199, 214; 199, 215; 201, 216; 201, 217; 202, 218; 202, 219; 204, 220; 204, 221; 207, 222; 207, 223; 207, 224; 208, 225; 209, 226; 211, 227; 216, 228; 216, 229; 217, 230; 217, 231; 218, 232; 218, 233; 219, 234; 219, 235; 219, 236; 223, 237; 223, 238; 224, 239; 224, 240; 225, 241; 225, 242; 226, 243; 226, 244; 240, 245; 242, 246; 242, 247; 243, 248; 243, 249; 244, 250; 244, 251; 246, 252; 246, 253; 247, 254; 247, 255 | def do_json_dupes_for_keys(self, params):
"""
\x1b[1mNAME\x1b[0m
json_duples_for_keys - Gets the duplicate znodes for the given keys
\x1b[1mSYNOPSIS\x1b[0m
json_dupes_for_keys <path> <keys> [prefix] [report_errors] [first]
\x1b[1mDESCRIPTION\x1b[0m
Znodes with duplicated keys are sorted and all but the first (original) one
are printed.
\x1b[1mOPTIONS\x1b[0m
* prefix: only include matching znodes
* report_errors: turn on error reporting (i.e.: bad JSON in a znode)
* first: print the first, non duplicated, znode too.
\x1b[1mEXAMPLES\x1b[0m
> json_cat /configs/primary_service true
member_0000000186
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
member_0000000187
{
"status": "ALIVE",
"serviceEndpoint": {
"http": {
"host": "10.0.0.2",
"port": 31994
}
},
"shard": 0
}
> json_dupes_for_keys /configs/primary_service shard
member_0000000187
"""
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
dupes_by_path = defaultdict(lambda: defaultdict(list))
for path, data in path_map.get():
parent, child = split(path)
if not child.startswith(params.prefix):
continue
try:
value = Keys.value(json_deserialize(data), params.keys)
dupes_by_path[parent][value].append(path)
except BadJSON as ex:
if params.report_errors:
self.show_output("Path %s has bad JSON.", path)
except Keys.Missing as ex:
if params.report_errors:
self.show_output("Path %s is missing key %s.", path, ex)
dupes = []
for _, paths_by_value in dupes_by_path.items():
for _, paths in paths_by_value.items():
if len(paths) > 1:
paths.sort()
paths = paths if params.first else paths[1:]
for path in paths:
idx = bisect.bisect(dupes, path)
dupes.insert(idx, path)
for dup in dupes:
self.show_output(dup)
# if no dupes were found we call it a failure (i.e.: exit(1) from --run-once)
if len(dupes) == 0:
return False |
0, module; 1, function_definition; 2, function_name:add_property_orders; 3, parameters; 4, block; 5, identifier:query_proto; 6, list_splat_pattern; 7, expression_statement; 8, for_statement; 9, identifier:orders; 10, comment:"""Add ordering constraint for the given datastore.Query proto message.
Args:
query_proto: datastore.Query proto message.
orders: list of propertype name string, default to ascending
order and set descending if prefixed by '-'.
Usage:
>>> add_property_orders(query_proto, 'foo') # sort by foo asc
>>> add_property_orders(query_proto, '-bar') # sort by bar desc
"""; 11, identifier:order; 12, identifier:orders; 13, block; 14, expression_statement; 15, if_statement; 16, expression_statement; 17, assignment; 18, comparison_operator:order[0] == '-'; 19, block; 20, else_clause; 21, assignment; 22, identifier:proto; 23, call; 24, subscript; 25, string; 26, expression_statement; 27, expression_statement; 28, block; 29, attribute; 30, identifier:order; 31, attribute; 32, argument_list; 33, identifier:order; 34, integer:0; 35, string_content:-; 36, assignment; 37, assignment; 38, expression_statement; 39, attribute; 40, identifier:name; 41, attribute; 42, identifier:add; 43, identifier:order; 44, subscript; 45, attribute; 46, attribute; 47, assignment; 48, identifier:proto; 49, identifier:property; 50, identifier:query_proto; 51, identifier:order; 52, identifier:order; 53, slice; 54, identifier:proto; 55, identifier:direction; 56, attribute; 57, identifier:DESCENDING; 58, attribute; 59, attribute; 60, integer:1; 61, identifier:query_pb2; 62, identifier:PropertyOrder; 63, identifier:proto; 64, identifier:direction; 65, attribute; 66, identifier:ASCENDING; 67, identifier:query_pb2; 68, identifier:PropertyOrder | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 4, 7; 4, 8; 6, 9; 7, 10; 8, 11; 8, 12; 8, 13; 13, 14; 13, 15; 13, 16; 14, 17; 15, 18; 15, 19; 15, 20; 16, 21; 17, 22; 17, 23; 18, 24; 18, 25; 19, 26; 19, 27; 20, 28; 21, 29; 21, 30; 23, 31; 23, 32; 24, 33; 24, 34; 25, 35; 26, 36; 27, 37; 28, 38; 29, 39; 29, 40; 31, 41; 31, 42; 36, 43; 36, 44; 37, 45; 37, 46; 38, 47; 39, 48; 39, 49; 41, 50; 41, 51; 44, 52; 44, 53; 45, 54; 45, 55; 46, 56; 46, 57; 47, 58; 47, 59; 53, 60; 56, 61; 56, 62; 58, 63; 58, 64; 59, 65; 59, 66; 65, 67; 65, 68 | def add_property_orders(query_proto, *orders):
"""Add ordering constraint for the given datastore.Query proto message.
Args:
query_proto: datastore.Query proto message.
orders: list of propertype name string, default to ascending
order and set descending if prefixed by '-'.
Usage:
>>> add_property_orders(query_proto, 'foo') # sort by foo asc
>>> add_property_orders(query_proto, '-bar') # sort by bar desc
"""
for order in orders:
proto = query_proto.order.add()
if order[0] == '-':
order = order[1:]
proto.direction = query_pb2.PropertyOrder.DESCENDING
else:
proto.direction = query_pb2.PropertyOrder.ASCENDING
proto.property.name = order |
0, module; 1, function_definition; 2, function_name:check_levels; 3, parameters; 4, block; 5, identifier:imls; 6, identifier:imt; 7, default_parameter; 8, expression_statement; 9, if_statement; 10, identifier:min_iml; 11, float:1E-10; 12, comment:"""
Raise a ValueError if the given levels are invalid.
:param imls: a list of intensity measure and levels
:param imt: the intensity measure type
:param min_iml: minimum intensity measure level (default 1E-10)
>>> check_levels([0.1, 0.2], 'PGA') # ok
>>> check_levels([], 'PGA')
Traceback (most recent call last):
...
ValueError: No imls for PGA: []
>>> check_levels([0.2, 0.1], 'PGA')
Traceback (most recent call last):
...
ValueError: The imls for PGA are not sorted: [0.2, 0.1]
>>> check_levels([0.2, 0.2], 'PGA')
Traceback (most recent call last):
...
ValueError: Found duplicated levels for PGA: [0.2, 0.2]
"""; 13, comparison_operator:len(imls) < 1; 14, block; 15, elif_clause; 16, elif_clause; 17, elif_clause; 18, elif_clause; 19, call; 20, integer:1; 21, raise_statement; 22, comparison_operator:imls != sorted(imls); 23, block; 24, comparison_operator:len(distinct(imls)) < len(imls); 25, block; 26, boolean_operator; 27, comment:# apply the cutoff; 28, block; 29, boolean_operator; 30, comment:# apply the cutoff; 31, block; 32, identifier:len; 33, argument_list; 34, call; 35, identifier:imls; 36, call; 37, raise_statement; 38, call; 39, call; 40, raise_statement; 41, comparison_operator:imls[0] == 0; 42, comparison_operator:imls[1] <= min_iml; 43, raise_statement; 44, comparison_operator:imls[0] == 0; 45, comparison_operator:imls[1] > min_iml; 46, expression_statement; 47, identifier:imls; 48, identifier:ValueError; 49, argument_list; 50, identifier:sorted; 51, argument_list; 52, call; 53, identifier:len; 54, argument_list; 55, identifier:len; 56, argument_list; 57, call; 58, subscript; 59, integer:0; 60, subscript; 61, identifier:min_iml; 62, call; 63, subscript; 64, integer:0; 65, subscript; 66, identifier:min_iml; 67, assignment; 68, binary_operator:'No imls for %s: %s' % (imt, imls); 69, identifier:imls; 70, identifier:ValueError; 71, argument_list; 72, call; 73, identifier:imls; 74, identifier:ValueError; 75, argument_list; 76, identifier:imls; 77, integer:0; 78, identifier:imls; 79, integer:1; 80, identifier:ValueError; 81, argument_list; 82, identifier:imls; 83, integer:0; 84, identifier:imls; 85, integer:1; 86, subscript; 87, identifier:min_iml; 88, string; 89, tuple; 90, binary_operator:'The imls for %s are not sorted: %s' % (imt, imls); 91, identifier:distinct; 92, argument_list; 93, binary_operator:"Found duplicated levels for %s: %s" % (imt, imls); 94, binary_operator:"The min_iml %s=%s is larger than the second level "
"for %s" % (imt, min_iml, imls); 95, identifier:imls; 96, integer:0; 97, string_content:No imls for %s: %s; 98, identifier:imt; 99, identifier:imls; 100, string; 101, tuple; 102, identifier:imls; 103, string:"Found duplicated levels for %s: %s"; 104, tuple; 105, concatenated_string; 106, tuple; 107, string_content:The imls for %s are not sorted: %s; 108, identifier:imt; 109, identifier:imls; 110, identifier:imt; 111, identifier:imls; 112, string:"The min_iml %s=%s is larger than the second level "; 113, string:"for %s"; 114, identifier:imt; 115, identifier:min_iml; 116, identifier:imls | 0, 1; 1, 2; 1, 3; 1, 4; 3, 5; 3, 6; 3, 7; 4, 8; 4, 9; 7, 10; 7, 11; 8, 12; 9, 13; 9, 14; 9, 15; 9, 16; 9, 17; 9, 18; 13, 19; 13, 20; 14, 21; 15, 22; 15, 23; 16, 24; 16, 25; 17, 26; 17, 27; 17, 28; 18, 29; 18, 30; 18, 31; 19, 32; 19, 33; 21, 34; 22, 35; 22, 36; 23, 37; 24, 38; 24, 39; 25, 40; 26, 41; 26, 42; 28, 43; 29, 44; 29, 45; 31, 46; 33, 47; 34, 48; 34, 49; 36, 50; 36, 51; 37, 52; 38, 53; 38, 54; 39, 55; 39, 56; 40, 57; 41, 58; 41, 59; 42, 60; 42, 61; 43, 62; 44, 63; 44, 64; 45, 65; 45, 66; 46, 67; 49, 68; 51, 69; 52, 70; 52, 71; 54, 72; 56, 73; 57, 74; 57, 75; 58, 76; 58, 77; 60, 78; 60, 79; 62, 80; 62, 81; 63, 82; 63, 83; 65, 84; 65, 85; 67, 86; 67, 87; 68, 88; 68, 89; 71, 90; 72, 91; 72, 92; 75, 93; 81, 94; 86, 95; 86, 96; 88, 97; 89, 98; 89, 99; 90, 100; 90, 101; 92, 102; 93, 103; 93, 104; 94, 105; 94, 106; 100, 107; 101, 108; 101, 109; 104, 110; 104, 111; 105, 112; 105, 113; 106, 114; 106, 115; 106, 116 | def check_levels(imls, imt, min_iml=1E-10):
"""
Raise a ValueError if the given levels are invalid.
:param imls: a list of intensity measure and levels
:param imt: the intensity measure type
:param min_iml: minimum intensity measure level (default 1E-10)
>>> check_levels([0.1, 0.2], 'PGA') # ok
>>> check_levels([], 'PGA')
Traceback (most recent call last):
...
ValueError: No imls for PGA: []
>>> check_levels([0.2, 0.1], 'PGA')
Traceback (most recent call last):
...
ValueError: The imls for PGA are not sorted: [0.2, 0.1]
>>> check_levels([0.2, 0.2], 'PGA')
Traceback (most recent call last):
...
ValueError: Found duplicated levels for PGA: [0.2, 0.2]
"""
if len(imls) < 1:
raise ValueError('No imls for %s: %s' % (imt, imls))
elif imls != sorted(imls):
raise ValueError('The imls for %s are not sorted: %s' % (imt, imls))
elif len(distinct(imls)) < len(imls):
raise ValueError("Found duplicated levels for %s: %s" % (imt, imls))
elif imls[0] == 0 and imls[1] <= min_iml: # apply the cutoff
raise ValueError("The min_iml %s=%s is larger than the second level "
"for %s" % (imt, min_iml, imls))
elif imls[0] == 0 and imls[1] > min_iml: # apply the cutoff
imls[0] = min_iml |
Subsets and Splits