sequence
stringlengths
546
16.2k
code
stringlengths
108
19.3k
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:get_sh_ids; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:identity; 6, identifier:backend_name; 7, block; 7, 8; 7, 10; 7, 11; 7, 22; 7, 32; 8, expression_statement; 8, 9; 9, comment; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:identity_tuple; 14, call; 14, 15; 14, 16; 15, identifier:tuple; 16, argument_list; 16, 17; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:identity; 20, identifier:items; 21, argument_list; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:sh_ids; 25, call; 25, 26; 25, 29; 26, attribute; 26, 27; 26, 28; 27, identifier:self; 28, identifier:__get_sh_ids_cache; 29, argument_list; 29, 30; 29, 31; 30, identifier:identity_tuple; 31, identifier:backend_name; 32, return_statement; 32, 33; 33, identifier:sh_ids
def get_sh_ids(self, identity, backend_name): """ Return the Sorting Hat id and uuid for an identity """ # Convert the dict to tuple so it is hashable identity_tuple = tuple(identity.items()) sh_ids = self.__get_sh_ids_cache(identity_tuple, backend_name) return sh_ids
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:get_sh_identity; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:item; 6, default_parameter; 6, 7; 6, 8; 7, identifier:identity_field; 8, None; 9, block; 9, 10; 9, 12; 9, 64; 9, 68; 9, 82; 9, 86; 9, 87; 9, 107; 9, 115; 10, expression_statement; 10, 11; 11, comment; 12, function_definition; 12, 13; 12, 14; 12, 17; 13, function_name:fill_list_identity; 14, parameters; 14, 15; 14, 16; 15, identifier:identity; 16, identifier:user_list_data; 17, block; 17, 18; 17, 20; 17, 30; 17, 45; 17, 62; 18, expression_statement; 18, 19; 19, comment; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 25; 22, subscript; 22, 23; 22, 24; 23, identifier:identity; 24, string:'username'; 25, subscript; 25, 26; 25, 29; 26, subscript; 26, 27; 26, 28; 27, identifier:user_list_data; 28, integer:0; 29, string:'__text__'; 30, if_statement; 30, 31; 30, 36; 31, comparison_operator:in; 31, 32; 31, 33; 32, string:'@'; 33, subscript; 33, 34; 33, 35; 34, identifier:identity; 35, string:'username'; 36, block; 36, 37; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 42; 39, subscript; 39, 40; 39, 41; 40, identifier:identity; 41, string:'email'; 42, subscript; 42, 43; 42, 44; 43, identifier:identity; 44, string:'username'; 45, if_statement; 45, 46; 45, 51; 46, comparison_operator:in; 46, 47; 46, 48; 47, string:'name'; 48, subscript; 48, 49; 48, 50; 49, identifier:user_list_data; 50, integer:0; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 57; 54, subscript; 54, 55; 54, 56; 55, identifier:identity; 56, string:'name'; 57, subscript; 57, 58; 57, 61; 58, subscript; 58, 59; 58, 60; 59, identifier:user_list_data; 60, integer:0; 61, string:'name'; 62, return_statement; 62, 63; 63, identifier:identity; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:identity; 67, dictionary; 68, for_statement; 68, 69; 68, 70; 68, 74; 68, 75; 69, identifier:field; 70, list:['name', 'email', 'username']; 70, 71; 70, 72; 70, 73; 71, string:'name'; 72, string:'email'; 73, string:'username'; 74, comment; 75, block; 75, 76; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 81; 78, subscript; 78, 79; 78, 80; 79, identifier:identity; 80, identifier:field; 81, None; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:user; 85, identifier:item; 86, comment; 87, if_statement; 87, 88; 87, 98; 88, boolean_operator:and; 88, 89; 88, 92; 89, comparison_operator:in; 89, 90; 89, 91; 90, string:'data'; 91, identifier:item; 92, comparison_operator:==; 92, 93; 92, 97; 93, call; 93, 94; 93, 95; 94, identifier:type; 95, argument_list; 95, 96; 96, identifier:item; 97, identifier:dict; 98, block; 98, 99; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:user; 102, subscript; 102, 103; 102, 106; 103, subscript; 103, 104; 103, 105; 104, identifier:item; 105, string:'data'; 106, identifier:identity_field; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:identity; 110, call; 110, 111; 110, 112; 111, identifier:fill_list_identity; 112, argument_list; 112, 113; 112, 114; 113, identifier:identity; 114, identifier:user; 115, return_statement; 115, 116; 116, identifier:identity
def get_sh_identity(self, item, identity_field=None): """ Return a Sorting Hat identity using bugzilla user data """ def fill_list_identity(identity, user_list_data): """ Fill identity with user data in first item in list """ identity['username'] = user_list_data[0]['__text__'] if '@' in identity['username']: identity['email'] = identity['username'] if 'name' in user_list_data[0]: identity['name'] = user_list_data[0]['name'] return identity identity = {} for field in ['name', 'email', 'username']: # Basic fields in Sorting Hat identity[field] = None user = item # by default a specific user dict is used if 'data' in item and type(item) == dict: user = item['data'][identity_field] identity = fill_list_identity(identity, user) return identity
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 23; 2, function_name:feed; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:from_date; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:from_offset; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:category; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:latest_items; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:arthur_items; 19, None; 20, default_parameter; 20, 21; 20, 22; 21, identifier:filter_classified; 22, None; 23, block; 23, 24; 23, 26; 23, 64; 23, 74; 23, 75; 23, 76; 23, 91; 23, 92; 23, 105; 23, 109; 23, 152; 23, 156; 23, 208; 23, 212; 23, 213; 23, 214; 23, 225; 23, 236; 23, 237; 23, 238; 23, 239; 23, 329; 23, 336; 24, expression_statement; 24, 25; 25, comment; 26, if_statement; 26, 27; 26, 30; 26, 49; 27, attribute; 27, 28; 27, 29; 28, identifier:self; 29, identifier:fetch_archive; 30, block; 30, 31; 30, 41; 30, 48; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:items; 34, call; 34, 35; 34, 40; 35, attribute; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:self; 38, identifier:perceval_backend; 39, identifier:fetch_from_archive; 40, argument_list; 41, expression_statement; 41, 42; 42, call; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:self; 45, identifier:feed_items; 46, argument_list; 46, 47; 47, identifier:items; 48, return_statement; 49, elif_clause; 49, 50; 49, 51; 50, identifier:arthur_items; 51, block; 51, 52; 51, 56; 51, 63; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 55; 54, identifier:items; 55, identifier:arthur_items; 56, expression_statement; 56, 57; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:self; 60, identifier:feed_items; 61, argument_list; 61, 62; 62, identifier:items; 63, return_statement; 64, if_statement; 64, 65; 64, 68; 65, boolean_operator:and; 65, 66; 65, 67; 66, identifier:from_date; 67, identifier:from_offset; 68, block; 68, 69; 69, raise_statement; 69, 70; 70, call; 70, 71; 70, 72; 71, identifier:RuntimeError; 72, argument_list; 72, 73; 73, string:"Can't not feed using from_date and from_offset."; 74, comment; 75, comment; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 79; 78, identifier:filters_; 79, list:[get_repository_filter(self.perceval_backend, self.get_connector_name())]; 79, 80; 80, call; 80, 81; 80, 82; 81, identifier:get_repository_filter; 82, argument_list; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:self; 85, identifier:perceval_backend; 86, call; 86, 87; 86, 90; 87, attribute; 87, 88; 87, 89; 88, identifier:self; 89, identifier:get_connector_name; 90, argument_list; 91, comment; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:signature; 95, call; 95, 96; 95, 99; 96, attribute; 96, 97; 96, 98; 97, identifier:inspect; 98, identifier:signature; 99, argument_list; 99, 100; 100, attribute; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:self; 103, identifier:perceval_backend; 104, identifier:fetch; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:last_update; 108, None; 109, if_statement; 109, 110; 109, 115; 110, comparison_operator:in; 110, 111; 110, 112; 111, string:'from_date'; 112, attribute; 112, 113; 112, 114; 113, identifier:signature; 114, identifier:parameters; 115, block; 115, 116; 115, 144; 116, if_statement; 116, 117; 116, 118; 116, 123; 117, identifier:from_date; 118, block; 118, 119; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:last_update; 122, identifier:from_date; 123, else_clause; 123, 124; 124, block; 124, 125; 124, 138; 125, expression_statement; 125, 126; 126, assignment; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:self; 129, identifier:last_update; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:self; 133, identifier:get_last_update_from_es; 134, argument_list; 134, 135; 135, keyword_argument; 135, 136; 135, 137; 136, identifier:filters_; 137, identifier:filters_; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:last_update; 141, attribute; 141, 142; 141, 143; 142, identifier:self; 143, identifier:last_update; 144, expression_statement; 144, 145; 145, call; 145, 146; 145, 149; 146, attribute; 146, 147; 146, 148; 147, identifier:logger; 148, identifier:info; 149, argument_list; 149, 150; 149, 151; 150, string:"Incremental from: %s"; 151, identifier:last_update; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:offset; 155, None; 156, if_statement; 156, 157; 156, 162; 157, comparison_operator:in; 157, 158; 157, 159; 158, string:'offset'; 159, attribute; 159, 160; 159, 161; 160, identifier:signature; 161, identifier:parameters; 162, block; 162, 163; 162, 186; 163, if_statement; 163, 164; 163, 165; 163, 170; 164, identifier:from_offset; 165, block; 165, 166; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 169; 168, identifier:offset; 169, identifier:from_offset; 170, else_clause; 170, 171; 171, block; 171, 172; 172, expression_statement; 172, 173; 173, assignment; 173, 174; 173, 175; 174, identifier:offset; 175, call; 175, 176; 175, 181; 176, attribute; 176, 177; 176, 180; 177, attribute; 177, 178; 177, 179; 178, identifier:self; 179, identifier:elastic; 180, identifier:get_last_offset; 181, argument_list; 181, 182; 181, 183; 182, string:"offset"; 183, keyword_argument; 183, 184; 183, 185; 184, identifier:filters_; 185, identifier:filters_; 186, if_statement; 186, 187; 186, 190; 186, 199; 187, comparison_operator:is; 187, 188; 187, 189; 188, identifier:offset; 189, None; 190, block; 190, 191; 191, expression_statement; 191, 192; 192, call; 192, 193; 192, 196; 193, attribute; 193, 194; 193, 195; 194, identifier:logger; 195, identifier:info; 196, argument_list; 196, 197; 196, 198; 197, string:"Incremental from: %i offset"; 198, identifier:offset; 199, else_clause; 199, 200; 200, block; 200, 201; 201, expression_statement; 201, 202; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:logger; 205, identifier:info; 206, argument_list; 206, 207; 207, string:"Not incremental"; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 211; 210, identifier:params; 211, dictionary; 212, comment; 213, comment; 214, if_statement; 214, 215; 214, 218; 215, comparison_operator:is; 215, 216; 215, 217; 216, identifier:category; 217, None; 218, block; 218, 219; 219, expression_statement; 219, 220; 220, assignment; 220, 221; 220, 224; 221, subscript; 221, 222; 221, 223; 222, identifier:params; 223, string:'category'; 224, identifier:category; 225, if_statement; 225, 226; 225, 229; 226, comparison_operator:is; 226, 227; 226, 228; 227, identifier:filter_classified; 228, None; 229, block; 229, 230; 230, expression_statement; 230, 231; 231, assignment; 231, 232; 231, 235; 232, subscript; 232, 233; 232, 234; 233, identifier:params; 234, string:'filter_classified'; 235, identifier:filter_classified; 236, comment; 237, comment; 238, comment; 239, if_statement; 239, 240; 239, 241; 239, 260; 239, 292; 239, 315; 240, identifier:latest_items; 241, block; 241, 242; 241, 248; 242, expression_statement; 242, 243; 243, assignment; 243, 244; 243, 247; 244, subscript; 244, 245; 244, 246; 245, identifier:params; 246, string:'latest_items'; 247, identifier:latest_items; 248, expression_statement; 248, 249; 249, assignment; 249, 250; 249, 251; 250, identifier:items; 251, call; 251, 252; 251, 257; 252, attribute; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:self; 255, identifier:perceval_backend; 256, identifier:fetch; 257, argument_list; 257, 258; 258, dictionary_splat; 258, 259; 259, identifier:params; 260, elif_clause; 260, 261; 260, 262; 261, identifier:last_update; 262, block; 262, 263; 262, 274; 262, 280; 263, expression_statement; 263, 264; 264, assignment; 264, 265; 264, 266; 265, identifier:last_update; 266, call; 266, 267; 266, 270; 267, attribute; 267, 268; 267, 269; 268, identifier:last_update; 269, identifier:replace; 270, argument_list; 270, 271; 271, keyword_argument; 271, 272; 271, 273; 272, identifier:tzinfo; 273, None; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 279; 276, subscript; 276, 277; 276, 278; 277, identifier:params; 278, string:'from_date'; 279, identifier:last_update; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:items; 283, call; 283, 284; 283, 289; 284, attribute; 284, 285; 284, 288; 285, attribute; 285, 286; 285, 287; 286, identifier:self; 287, identifier:perceval_backend; 288, identifier:fetch; 289, argument_list; 289, 290; 290, dictionary_splat; 290, 291; 291, identifier:params; 292, elif_clause; 292, 293; 292, 296; 293, comparison_operator:is; 293, 294; 293, 295; 294, identifier:offset; 295, None; 296, block; 296, 297; 296, 303; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 302; 299, subscript; 299, 300; 299, 301; 300, identifier:params; 301, string:'offset'; 302, identifier:offset; 303, expression_statement; 303, 304; 304, assignment; 304, 305; 304, 306; 305, identifier:items; 306, call; 306, 307; 306, 312; 307, attribute; 307, 308; 307, 311; 308, attribute; 308, 309; 308, 310; 309, identifier:self; 310, identifier:perceval_backend; 311, identifier:fetch; 312, argument_list; 312, 313; 313, dictionary_splat; 313, 314; 314, identifier:params; 315, else_clause; 315, 316; 316, block; 316, 317; 317, expression_statement; 317, 318; 318, assignment; 318, 319; 318, 320; 319, identifier:items; 320, call; 320, 321; 320, 326; 321, attribute; 321, 322; 321, 325; 322, attribute; 322, 323; 322, 324; 323, identifier:self; 324, identifier:perceval_backend; 325, identifier:fetch; 326, argument_list; 326, 327; 327, dictionary_splat; 327, 328; 328, identifier:params; 329, expression_statement; 329, 330; 330, call; 330, 331; 330, 334; 331, attribute; 331, 332; 331, 333; 332, identifier:self; 333, identifier:feed_items; 334, argument_list; 334, 335; 335, identifier:items; 336, expression_statement; 336, 337; 337, call; 337, 338; 337, 341; 338, attribute; 338, 339; 338, 340; 339, identifier:self; 340, identifier:update_items; 341, argument_list
def feed(self, from_date=None, from_offset=None, category=None, latest_items=None, arthur_items=None, filter_classified=None): """ Feed data in Elastic from Perceval or Arthur """ if self.fetch_archive: items = self.perceval_backend.fetch_from_archive() self.feed_items(items) return elif arthur_items: items = arthur_items self.feed_items(items) return if from_date and from_offset: raise RuntimeError("Can't not feed using from_date and from_offset.") # We need to filter by repository to support several repositories # in the same raw index filters_ = [get_repository_filter(self.perceval_backend, self.get_connector_name())] # Check if backend supports from_date signature = inspect.signature(self.perceval_backend.fetch) last_update = None if 'from_date' in signature.parameters: if from_date: last_update = from_date else: self.last_update = self.get_last_update_from_es(filters_=filters_) last_update = self.last_update logger.info("Incremental from: %s", last_update) offset = None if 'offset' in signature.parameters: if from_offset: offset = from_offset else: offset = self.elastic.get_last_offset("offset", filters_=filters_) if offset is not None: logger.info("Incremental from: %i offset", offset) else: logger.info("Not incremental") params = {} # category and filter_classified params are shared # by all Perceval backends if category is not None: params['category'] = category if filter_classified is not None: params['filter_classified'] = filter_classified # latest items, from_date and offset cannot be used together, # thus, the params dictionary is filled with the param available # and Perceval is executed if latest_items: params['latest_items'] = latest_items items = self.perceval_backend.fetch(**params) elif last_update: last_update = last_update.replace(tzinfo=None) params['from_date'] = last_update items = self.perceval_backend.fetch(**params) elif offset is not None: params['offset'] = offset items = self.perceval_backend.fetch(**params) else: items = self.perceval_backend.fetch(**params) self.feed_items(items) self.update_items()
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:get_identities; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:item; 6, block; 6, 7; 6, 9; 6, 163; 6, 171; 6, 278; 6, 384; 7, expression_statement; 7, 8; 8, comment; 9, function_definition; 9, 10; 9, 11; 9, 15; 10, function_name:add_sh_github_identity; 11, parameters; 11, 12; 11, 13; 11, 14; 12, identifier:user; 13, identifier:user_field; 14, identifier:rol; 15, block; 15, 16; 15, 18; 15, 22; 15, 52; 15, 57; 15, 58; 15, 66; 15, 79; 16, expression_statement; 16, 17; 17, comment; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:github_repo; 21, None; 22, if_statement; 22, 23; 22, 28; 23, comparison_operator:in; 23, 24; 23, 25; 24, identifier:GITHUB; 25, subscript; 25, 26; 25, 27; 26, identifier:item; 27, string:'origin'; 28, block; 28, 29; 28, 41; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:github_repo; 32, call; 32, 33; 32, 38; 33, attribute; 33, 34; 33, 37; 34, subscript; 34, 35; 34, 36; 35, identifier:item; 36, string:'origin'; 37, identifier:replace; 38, argument_list; 38, 39; 38, 40; 39, identifier:GITHUB; 40, string:''; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:github_repo; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:re; 47, identifier:sub; 48, argument_list; 48, 49; 48, 50; 48, 51; 49, string:'.git$'; 50, string:''; 51, identifier:github_repo; 52, if_statement; 52, 53; 52, 55; 53, not_operator; 53, 54; 54, identifier:github_repo; 55, block; 55, 56; 56, return_statement; 57, comment; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:user_data; 61, subscript; 61, 62; 61, 65; 62, subscript; 62, 63; 62, 64; 63, identifier:item; 64, string:'data'; 65, identifier:user_field; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:sh_identity; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:SortingHat; 72, identifier:get_github_commit_username; 73, argument_list; 73, 74; 73, 77; 73, 78; 74, attribute; 74, 75; 74, 76; 75, identifier:self; 76, identifier:sh_db; 77, identifier:user; 78, identifier:SH_GIT_COMMIT; 79, if_statement; 79, 80; 79, 82; 79, 83; 79, 133; 80, not_operator; 80, 81; 81, identifier:sh_identity; 82, comment; 83, block; 83, 84; 83, 96; 83, 97; 83, 107; 83, 116; 83, 122; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:gh_username; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:self; 90, identifier:get_github_login; 91, argument_list; 91, 92; 91, 93; 91, 94; 91, 95; 92, identifier:user_data; 93, identifier:rol; 94, identifier:commit_hash; 95, identifier:github_repo; 96, comment; 97, expression_statement; 97, 98; 98, call; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, identifier:logger; 101, identifier:debug; 102, argument_list; 102, 103; 102, 104; 102, 105; 102, 106; 103, string:"Adding new identity %s to SH %s: %s"; 104, identifier:gh_username; 105, identifier:SH_GIT_COMMIT; 106, identifier:user; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:user; 110, call; 110, 111; 110, 114; 111, attribute; 111, 112; 111, 113; 112, identifier:self; 113, identifier:get_sh_identity; 114, argument_list; 114, 115; 115, identifier:user_data; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 121; 118, subscript; 118, 119; 118, 120; 119, identifier:user; 120, string:'username'; 121, identifier:gh_username; 122, expression_statement; 122, 123; 123, call; 123, 124; 123, 127; 124, attribute; 124, 125; 124, 126; 125, identifier:SortingHat; 126, identifier:add_identity; 127, argument_list; 127, 128; 127, 131; 127, 132; 128, attribute; 128, 129; 128, 130; 129, identifier:self; 130, identifier:sh_db; 131, identifier:user; 132, identifier:SH_GIT_COMMIT; 133, else_clause; 133, 134; 134, block; 134, 135; 135, if_statement; 135, 136; 135, 141; 136, comparison_operator:not; 136, 137; 136, 138; 137, identifier:user_data; 138, attribute; 138, 139; 138, 140; 139, identifier:self; 140, identifier:github_logins; 141, block; 141, 142; 141, 152; 142, expression_statement; 142, 143; 143, assignment; 143, 144; 143, 149; 144, subscript; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:self; 147, identifier:github_logins; 148, identifier:user_data; 149, subscript; 149, 150; 149, 151; 150, identifier:sh_identity; 151, string:'username'; 152, expression_statement; 152, 153; 153, call; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:logger; 156, identifier:debug; 157, argument_list; 157, 158; 157, 159; 157, 162; 158, string:"GitHub-commit exists. username:%s user:%s"; 159, subscript; 159, 160; 159, 161; 160, identifier:sh_identity; 161, string:'username'; 162, identifier:user_data; 163, expression_statement; 163, 164; 164, assignment; 164, 165; 164, 166; 165, identifier:commit_hash; 166, subscript; 166, 167; 166, 170; 167, subscript; 167, 168; 167, 169; 168, identifier:item; 169, string:'data'; 170, string:'commit'; 171, if_statement; 171, 172; 171, 177; 171, 178; 172, subscript; 172, 173; 172, 176; 173, subscript; 173, 174; 173, 175; 174, identifier:item; 175, string:'data'; 176, string:'Author'; 177, comment; 178, block; 178, 179; 178, 194; 178, 209; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:m; 182, call; 182, 183; 182, 188; 183, attribute; 183, 184; 183, 187; 184, attribute; 184, 185; 184, 186; 185, identifier:self; 186, identifier:AUTHOR_P2P_REGEX; 187, identifier:match; 188, argument_list; 188, 189; 189, subscript; 189, 190; 189, 193; 190, subscript; 190, 191; 190, 192; 191, identifier:item; 192, string:'data'; 193, string:"Author"; 194, expression_statement; 194, 195; 195, assignment; 195, 196; 195, 197; 196, identifier:n; 197, call; 197, 198; 197, 203; 198, attribute; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, identifier:self; 201, identifier:AUTHOR_P2P_NEW_REGEX; 202, identifier:match; 203, argument_list; 203, 204; 204, subscript; 204, 205; 204, 208; 205, subscript; 205, 206; 205, 207; 206, identifier:item; 207, string:'data'; 208, string:"Author"; 209, if_statement; 209, 210; 209, 218; 209, 248; 210, boolean_operator:and; 210, 211; 210, 215; 211, parenthesized_expression; 211, 212; 212, boolean_operator:or; 212, 213; 212, 214; 213, identifier:m; 214, identifier:n; 215, attribute; 215, 216; 215, 217; 216, identifier:self; 217, identifier:pair_programming; 218, block; 218, 219; 218, 232; 219, expression_statement; 219, 220; 220, assignment; 220, 221; 220, 222; 221, identifier:authors; 222, call; 222, 223; 222, 226; 223, attribute; 223, 224; 223, 225; 224, identifier:self; 225, identifier:__get_authors; 226, argument_list; 226, 227; 227, subscript; 227, 228; 227, 231; 228, subscript; 228, 229; 228, 230; 229, identifier:item; 230, string:'data'; 231, string:"Author"; 232, for_statement; 232, 233; 232, 234; 232, 235; 233, identifier:author; 234, identifier:authors; 235, block; 235, 236; 235, 245; 236, expression_statement; 236, 237; 237, assignment; 237, 238; 237, 239; 238, identifier:user; 239, call; 239, 240; 239, 243; 240, attribute; 240, 241; 240, 242; 241, identifier:self; 242, identifier:get_sh_identity; 243, argument_list; 243, 244; 244, identifier:author; 245, expression_statement; 245, 246; 246, yield; 246, 247; 247, identifier:user; 248, else_clause; 248, 249; 249, block; 249, 250; 249, 263; 249, 266; 250, expression_statement; 250, 251; 251, assignment; 251, 252; 251, 253; 252, identifier:user; 253, call; 253, 254; 253, 257; 254, attribute; 254, 255; 254, 256; 255, identifier:self; 256, identifier:get_sh_identity; 257, argument_list; 257, 258; 258, subscript; 258, 259; 258, 262; 259, subscript; 259, 260; 259, 261; 260, identifier:item; 261, string:'data'; 262, string:"Author"; 263, expression_statement; 263, 264; 264, yield; 264, 265; 265, identifier:user; 266, if_statement; 266, 267; 266, 270; 267, attribute; 267, 268; 267, 269; 268, identifier:self; 269, identifier:github_token; 270, block; 270, 271; 271, expression_statement; 271, 272; 272, call; 272, 273; 272, 274; 273, identifier:add_sh_github_identity; 274, argument_list; 274, 275; 274, 276; 274, 277; 275, identifier:user; 276, string:'Author'; 277, string:'author'; 278, if_statement; 278, 279; 278, 284; 279, subscript; 279, 280; 279, 283; 280, subscript; 280, 281; 280, 282; 281, identifier:item; 282, string:'data'; 283, string:'Commit'; 284, block; 284, 285; 284, 300; 284, 315; 285, expression_statement; 285, 286; 286, assignment; 286, 287; 286, 288; 287, identifier:m; 288, call; 288, 289; 288, 294; 289, attribute; 289, 290; 289, 293; 290, attribute; 290, 291; 290, 292; 291, identifier:self; 292, identifier:AUTHOR_P2P_REGEX; 293, identifier:match; 294, argument_list; 294, 295; 295, subscript; 295, 296; 295, 299; 296, subscript; 296, 297; 296, 298; 297, identifier:item; 298, string:'data'; 299, string:"Commit"; 300, expression_statement; 300, 301; 301, assignment; 301, 302; 301, 303; 302, identifier:n; 303, call; 303, 304; 303, 309; 304, attribute; 304, 305; 304, 308; 305, attribute; 305, 306; 305, 307; 306, identifier:self; 307, identifier:AUTHOR_P2P_NEW_REGEX; 308, identifier:match; 309, argument_list; 309, 310; 310, subscript; 310, 311; 310, 314; 311, subscript; 311, 312; 311, 313; 312, identifier:item; 313, string:'data'; 314, string:"Author"; 315, if_statement; 315, 316; 315, 324; 315, 354; 316, boolean_operator:and; 316, 317; 316, 321; 317, parenthesized_expression; 317, 318; 318, boolean_operator:or; 318, 319; 318, 320; 319, identifier:m; 320, identifier:n; 321, attribute; 321, 322; 321, 323; 322, identifier:self; 323, identifier:pair_programming; 324, block; 324, 325; 324, 338; 325, expression_statement; 325, 326; 326, assignment; 326, 327; 326, 328; 327, identifier:committers; 328, call; 328, 329; 328, 332; 329, attribute; 329, 330; 329, 331; 330, identifier:self; 331, identifier:__get_authors; 332, argument_list; 332, 333; 333, subscript; 333, 334; 333, 337; 334, subscript; 334, 335; 334, 336; 335, identifier:item; 336, string:'data'; 337, string:'Commit'; 338, for_statement; 338, 339; 338, 340; 338, 341; 339, identifier:committer; 340, identifier:committers; 341, block; 341, 342; 341, 351; 342, expression_statement; 342, 343; 343, assignment; 343, 344; 343, 345; 344, identifier:user; 345, call; 345, 346; 345, 349; 346, attribute; 346, 347; 346, 348; 347, identifier:self; 348, identifier:get_sh_identity; 349, argument_list; 349, 350; 350, identifier:committer; 351, expression_statement; 351, 352; 352, yield; 352, 353; 353, identifier:user; 354, else_clause; 354, 355; 355, block; 355, 356; 355, 369; 355, 372; 356, expression_statement; 356, 357; 357, assignment; 357, 358; 357, 359; 358, identifier:user; 359, call; 359, 360; 359, 363; 360, attribute; 360, 361; 360, 362; 361, identifier:self; 362, identifier:get_sh_identity; 363, argument_list; 363, 364; 364, subscript; 364, 365; 364, 368; 365, subscript; 365, 366; 365, 367; 366, identifier:item; 367, string:'data'; 368, string:'Commit'; 369, expression_statement; 369, 370; 370, yield; 370, 371; 371, identifier:user; 372, if_statement; 372, 373; 372, 376; 373, attribute; 373, 374; 373, 375; 374, identifier:self; 375, identifier:github_token; 376, block; 376, 377; 377, expression_statement; 377, 378; 378, call; 378, 379; 378, 380; 379, identifier:add_sh_github_identity; 380, argument_list; 380, 381; 380, 382; 380, 383; 381, identifier:user; 382, string:'Commit'; 383, string:'committer'; 384, if_statement; 384, 385; 384, 394; 385, boolean_operator:and; 385, 386; 385, 391; 386, comparison_operator:in; 386, 387; 386, 388; 387, string:'Signed-off-by'; 388, subscript; 388, 389; 388, 390; 389, identifier:item; 390, string:'data'; 391, attribute; 391, 392; 391, 393; 392, identifier:self; 393, identifier:pair_programming; 394, block; 394, 395; 394, 403; 395, expression_statement; 395, 396; 396, assignment; 396, 397; 396, 398; 397, identifier:signers; 398, subscript; 398, 399; 398, 402; 399, subscript; 399, 400; 399, 401; 400, identifier:item; 401, string:'data'; 402, string:"Signed-off-by"; 403, for_statement; 403, 404; 403, 405; 403, 406; 404, identifier:signer; 405, identifier:signers; 406, block; 406, 407; 406, 416; 407, expression_statement; 407, 408; 408, assignment; 408, 409; 408, 410; 409, identifier:user; 410, call; 410, 411; 410, 414; 411, attribute; 411, 412; 411, 413; 412, identifier:self; 413, identifier:get_sh_identity; 414, argument_list; 414, 415; 415, identifier:signer; 416, expression_statement; 416, 417; 417, yield; 417, 418; 418, identifier:user
def get_identities(self, item): """ Return the identities from an item. If the repo is in GitHub, get the usernames from GitHub. """ def add_sh_github_identity(user, user_field, rol): """ Add a new github identity to SH if it does not exists """ github_repo = None if GITHUB in item['origin']: github_repo = item['origin'].replace(GITHUB, '') github_repo = re.sub('.git$', '', github_repo) if not github_repo: return # Try to get the identity from SH user_data = item['data'][user_field] sh_identity = SortingHat.get_github_commit_username(self.sh_db, user, SH_GIT_COMMIT) if not sh_identity: # Get the usename from GitHub gh_username = self.get_github_login(user_data, rol, commit_hash, github_repo) # Create a new SH identity with name, email from git and username from github logger.debug("Adding new identity %s to SH %s: %s", gh_username, SH_GIT_COMMIT, user) user = self.get_sh_identity(user_data) user['username'] = gh_username SortingHat.add_identity(self.sh_db, user, SH_GIT_COMMIT) else: if user_data not in self.github_logins: self.github_logins[user_data] = sh_identity['username'] logger.debug("GitHub-commit exists. username:%s user:%s", sh_identity['username'], user_data) commit_hash = item['data']['commit'] if item['data']['Author']: # Check multi authors commits m = self.AUTHOR_P2P_REGEX.match(item['data']["Author"]) n = self.AUTHOR_P2P_NEW_REGEX.match(item['data']["Author"]) if (m or n) and self.pair_programming: authors = self.__get_authors(item['data']["Author"]) for author in authors: user = self.get_sh_identity(author) yield user else: user = self.get_sh_identity(item['data']["Author"]) yield user if self.github_token: add_sh_github_identity(user, 'Author', 'author') if item['data']['Commit']: m = self.AUTHOR_P2P_REGEX.match(item['data']["Commit"]) n = self.AUTHOR_P2P_NEW_REGEX.match(item['data']["Author"]) if (m or n) and self.pair_programming: committers = self.__get_authors(item['data']['Commit']) for committer in committers: user = self.get_sh_identity(committer) yield user else: user = self.get_sh_identity(item['data']['Commit']) yield user if self.github_token: add_sh_github_identity(user, 'Commit', 'committer') if 'Signed-off-by' in item['data'] and self.pair_programming: signers = item['data']["Signed-off-by"] for signer in signers: user = self.get_sh_identity(signer) yield user
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 10; 2, function_name:areas_of_code; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:git_enrich; 5, identifier:in_conn; 6, identifier:out_conn; 7, default_parameter; 7, 8; 7, 9; 8, identifier:block_size; 9, integer:100; 10, block; 10, 11; 10, 13; 10, 31; 10, 39; 11, expression_statement; 11, 12; 12, comment; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:aoc; 16, call; 16, 17; 16, 18; 17, identifier:AreasOfCode; 18, argument_list; 18, 19; 18, 22; 18, 25; 18, 28; 19, keyword_argument; 19, 20; 19, 21; 20, identifier:in_connector; 21, identifier:in_conn; 22, keyword_argument; 22, 23; 22, 24; 23, identifier:out_connector; 24, identifier:out_conn; 25, keyword_argument; 25, 26; 25, 27; 26, identifier:block_size; 27, identifier:block_size; 28, keyword_argument; 28, 29; 28, 30; 29, identifier:git_enrich; 30, identifier:git_enrich; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:ndocs; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:aoc; 37, identifier:analyze; 38, argument_list; 39, return_statement; 39, 40; 40, identifier:ndocs
def areas_of_code(git_enrich, in_conn, out_conn, block_size=100): """Build and index for areas of code from a given Perceval RAW index. :param block_size: size of items block. :param git_enrich: GitEnrich object to deal with SortingHat affiliations. :param in_conn: ESPandasConnector to read from. :param out_conn: ESPandasConnector to write to. :return: number of documents written in ElasticSearch enriched index. """ aoc = AreasOfCode(in_connector=in_conn, out_connector=out_conn, block_size=block_size, git_enrich=git_enrich) ndocs = aoc.analyze() return ndocs
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 1, 10; 2, function_name:_make_serializer; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, identifier:meas; 5, identifier:schema; 6, identifier:rm_none; 7, identifier:extra_tags; 8, identifier:placeholder; 9, comment; 10, block; 10, 11; 10, 13; 10, 19; 10, 23; 10, 27; 10, 31; 10, 35; 10, 180; 10, 186; 10, 203; 10, 214; 10, 221; 10, 228; 10, 232; 10, 268; 10, 274; 10, 297; 11, expression_statement; 11, 12; 12, comment; 13, expression_statement; 13, 14; 14, call; 14, 15; 14, 16; 15, identifier:_validate_schema; 16, argument_list; 16, 17; 16, 18; 17, identifier:schema; 18, identifier:placeholder; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:tags; 22, list:[]; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:fields; 26, list:[]; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:ts; 30, None; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:meas; 34, identifier:meas; 35, for_statement; 35, 36; 35, 39; 35, 44; 36, pattern_list; 36, 37; 36, 38; 37, identifier:k; 38, identifier:t; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:schema; 42, identifier:items; 43, argument_list; 44, block; 44, 45; 45, if_statement; 45, 46; 45, 49; 45, 54; 45, 63; 45, 81; 45, 99; 45, 111; 45, 123; 45, 137; 45, 149; 45, 161; 45, 173; 46, comparison_operator:is; 46, 47; 46, 48; 47, identifier:t; 48, identifier:MEASUREMENT; 49, block; 49, 50; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:meas; 53, string:f"{{i.{k}}}"; 54, elif_clause; 54, 55; 54, 58; 55, comparison_operator:is; 55, 56; 55, 57; 56, identifier:t; 57, identifier:TIMEINT; 58, block; 58, 59; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:ts; 62, string:f"{{i.{k}}}"; 63, elif_clause; 63, 64; 63, 67; 64, comparison_operator:is; 64, 65; 64, 66; 65, identifier:t; 66, identifier:TIMESTR; 67, block; 67, 68; 68, if_statement; 68, 69; 68, 70; 68, 75; 69, identifier:pd; 70, block; 70, 71; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:ts; 74, string:f"{{pd.Timestamp(i.{k} or 0).value}}"; 75, else_clause; 75, 76; 76, block; 76, 77; 77, expression_statement; 77, 78; 78, assignment; 78, 79; 78, 80; 79, identifier:ts; 80, string:f"{{dt_to_int(str_to_dt(i.{k}))}}"; 81, elif_clause; 81, 82; 81, 85; 82, comparison_operator:is; 82, 83; 82, 84; 83, identifier:t; 84, identifier:TIMEDT; 85, block; 85, 86; 86, if_statement; 86, 87; 86, 88; 86, 93; 87, identifier:pd; 88, block; 88, 89; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:ts; 92, string:f"{{pd.Timestamp(i.{k} or 0).value}}"; 93, else_clause; 93, 94; 94, block; 94, 95; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:ts; 98, string:f"{{dt_to_int(i.{k})}}"; 99, elif_clause; 99, 100; 99, 103; 100, comparison_operator:is; 100, 101; 100, 102; 101, identifier:t; 102, identifier:TAG; 103, block; 103, 104; 104, expression_statement; 104, 105; 105, call; 105, 106; 105, 109; 106, attribute; 106, 107; 106, 108; 107, identifier:tags; 108, identifier:append; 109, argument_list; 109, 110; 110, string:f"{k}={{str(i.{k}).translate(tag_escape)}}"; 111, elif_clause; 111, 112; 111, 115; 112, comparison_operator:is; 112, 113; 112, 114; 113, identifier:t; 114, identifier:TAGENUM; 115, block; 115, 116; 116, expression_statement; 116, 117; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:tags; 120, identifier:append; 121, argument_list; 121, 122; 122, string:f"{k}={{getattr(i.{k}, 'name', i.{k} or None)}}"; 123, elif_clause; 123, 124; 123, 129; 124, comparison_operator:in; 124, 125; 124, 126; 125, identifier:t; 126, tuple; 126, 127; 126, 128; 127, identifier:FLOAT; 128, identifier:BOOL; 129, block; 129, 130; 130, expression_statement; 130, 131; 131, call; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:fields; 134, identifier:append; 135, argument_list; 135, 136; 136, string:f"{k}={{i.{k}}}"; 137, elif_clause; 137, 138; 137, 141; 138, comparison_operator:is; 138, 139; 138, 140; 139, identifier:t; 140, identifier:INT; 141, block; 141, 142; 142, expression_statement; 142, 143; 143, call; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:fields; 146, identifier:append; 147, argument_list; 147, 148; 148, string:f"{k}={{i.{k}}}i"; 149, elif_clause; 149, 150; 149, 153; 150, comparison_operator:is; 150, 151; 150, 152; 151, identifier:t; 152, identifier:STR; 153, block; 153, 154; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:fields; 158, identifier:append; 159, argument_list; 159, 160; 160, string:f"{k}=\\\"{{str(i.{k}).translate(str_escape)}}\\\""; 161, elif_clause; 161, 162; 161, 165; 162, comparison_operator:is; 162, 163; 162, 164; 163, identifier:t; 164, identifier:ENUM; 165, block; 165, 166; 166, expression_statement; 166, 167; 167, call; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:fields; 170, identifier:append; 171, argument_list; 171, 172; 172, string:f"{k}=\\\"{{getattr(i.{k}, 'name', i.{k} or None)}}\\\""; 173, else_clause; 173, 174; 174, block; 174, 175; 175, raise_statement; 175, 176; 176, call; 176, 177; 176, 178; 177, identifier:SchemaError; 178, argument_list; 178, 179; 179, string:f"Invalid attribute type {k!r}: {t!r}"; 180, expression_statement; 180, 181; 181, assignment; 181, 182; 181, 183; 182, identifier:extra_tags; 183, boolean_operator:or; 183, 184; 183, 185; 184, identifier:extra_tags; 185, dictionary; 186, for_statement; 186, 187; 186, 190; 186, 195; 187, pattern_list; 187, 188; 187, 189; 188, identifier:k; 189, identifier:v; 190, call; 190, 191; 190, 194; 191, attribute; 191, 192; 191, 193; 192, identifier:extra_tags; 193, identifier:items; 194, argument_list; 195, block; 195, 196; 196, expression_statement; 196, 197; 197, call; 197, 198; 197, 201; 198, attribute; 198, 199; 198, 200; 199, identifier:tags; 200, identifier:append; 201, argument_list; 201, 202; 202, string:f"{k}={v}"; 203, if_statement; 203, 204; 203, 205; 204, identifier:placeholder; 205, block; 205, 206; 206, expression_statement; 206, 207; 207, call; 207, 208; 207, 211; 208, attribute; 208, 209; 208, 210; 209, identifier:fields; 210, identifier:insert; 211, argument_list; 211, 212; 211, 213; 212, integer:0; 213, string:f"_=true"; 214, expression_statement; 214, 215; 215, assignment; 215, 216; 215, 217; 216, identifier:sep; 217, conditional_expression:if; 217, 218; 217, 219; 217, 220; 218, string:','; 219, identifier:tags; 220, string:''; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 224; 223, identifier:ts; 224, conditional_expression:if; 224, 225; 224, 226; 224, 227; 225, string:f' {ts}'; 226, identifier:ts; 227, string:''; 228, expression_statement; 228, 229; 229, assignment; 229, 230; 229, 231; 230, identifier:fmt; 231, string:f"{meas}{sep}{','.join(tags)} {','.join(fields)}{ts}"; 232, if_statement; 232, 233; 232, 234; 232, 235; 232, 236; 232, 254; 233, identifier:rm_none; 234, comment; 235, comment; 236, block; 236, 237; 236, 241; 237, expression_statement; 237, 238; 238, assignment; 238, 239; 238, 240; 239, identifier:pat; 240, string:r',\w+="?None"?i?'; 241, expression_statement; 241, 242; 242, assignment; 242, 243; 242, 244; 243, identifier:f; 244, call; 244, 245; 244, 246; 245, identifier:eval; 246, argument_list; 246, 247; 247, call; 247, 248; 247, 251; 248, attribute; 248, 249; 248, 250; 249, string:'lambda i: re.sub(r\'{}\', "", f"{}").encode()'; 250, identifier:format; 251, argument_list; 251, 252; 251, 253; 252, identifier:pat; 253, identifier:fmt; 254, else_clause; 254, 255; 255, block; 255, 256; 256, expression_statement; 256, 257; 257, assignment; 257, 258; 257, 259; 258, identifier:f; 259, call; 259, 260; 259, 261; 260, identifier:eval; 261, argument_list; 261, 262; 262, call; 262, 263; 262, 266; 263, attribute; 263, 264; 263, 265; 264, string:'lambda i: f"{}".encode()'; 265, identifier:format; 266, argument_list; 266, 267; 267, identifier:fmt; 268, expression_statement; 268, 269; 269, assignment; 269, 270; 269, 273; 270, attribute; 270, 271; 270, 272; 271, identifier:f; 272, identifier:__doc__; 273, string:"Returns InfluxDB line protocol representation of user-defined class"; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:f; 278, identifier:_args; 279, call; 279, 280; 279, 281; 280, identifier:dict; 281, argument_list; 281, 282; 281, 285; 281, 288; 281, 291; 281, 294; 282, keyword_argument; 282, 283; 282, 284; 283, identifier:meas; 284, identifier:meas; 285, keyword_argument; 285, 286; 285, 287; 286, identifier:schema; 287, identifier:schema; 288, keyword_argument; 288, 289; 288, 290; 289, identifier:rm_none; 290, identifier:rm_none; 291, keyword_argument; 291, 292; 291, 293; 292, identifier:extra_tags; 293, identifier:extra_tags; 294, keyword_argument; 294, 295; 294, 296; 295, identifier:placeholder; 296, identifier:placeholder; 297, return_statement; 297, 298; 298, identifier:f
def _make_serializer(meas, schema, rm_none, extra_tags, placeholder): # noqa: C901 """Factory of line protocol parsers""" _validate_schema(schema, placeholder) tags = [] fields = [] ts = None meas = meas for k, t in schema.items(): if t is MEASUREMENT: meas = f"{{i.{k}}}" elif t is TIMEINT: ts = f"{{i.{k}}}" elif t is TIMESTR: if pd: ts = f"{{pd.Timestamp(i.{k} or 0).value}}" else: ts = f"{{dt_to_int(str_to_dt(i.{k}))}}" elif t is TIMEDT: if pd: ts = f"{{pd.Timestamp(i.{k} or 0).value}}" else: ts = f"{{dt_to_int(i.{k})}}" elif t is TAG: tags.append(f"{k}={{str(i.{k}).translate(tag_escape)}}") elif t is TAGENUM: tags.append(f"{k}={{getattr(i.{k}, 'name', i.{k} or None)}}") elif t in (FLOAT, BOOL): fields.append(f"{k}={{i.{k}}}") elif t is INT: fields.append(f"{k}={{i.{k}}}i") elif t is STR: fields.append(f"{k}=\\\"{{str(i.{k}).translate(str_escape)}}\\\"") elif t is ENUM: fields.append(f"{k}=\\\"{{getattr(i.{k}, 'name', i.{k} or None)}}\\\"") else: raise SchemaError(f"Invalid attribute type {k!r}: {t!r}") extra_tags = extra_tags or {} for k, v in extra_tags.items(): tags.append(f"{k}={v}") if placeholder: fields.insert(0, f"_=true") sep = ',' if tags else '' ts = f' {ts}' if ts else '' fmt = f"{meas}{sep}{','.join(tags)} {','.join(fields)}{ts}" if rm_none: # Has substantial runtime impact. Best avoided if performance is critical. # First field can't be removed. pat = r',\w+="?None"?i?' f = eval('lambda i: re.sub(r\'{}\', "", f"{}").encode()'.format(pat, fmt)) else: f = eval('lambda i: f"{}".encode()'.format(fmt)) f.__doc__ = "Returns InfluxDB line protocol representation of user-defined class" f._args = dict(meas=meas, schema=schema, rm_none=rm_none, extra_tags=extra_tags, placeholder=placeholder) return f
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 1, 23; 2, function_name:iterpoints; 3, parameters; 3, 4; 3, 8; 4, typed_parameter; 4, 5; 4, 6; 5, identifier:resp; 6, type; 6, 7; 7, identifier:dict; 8, typed_default_parameter; 8, 9; 8, 10; 8, 16; 9, identifier:parser; 10, type; 10, 11; 11, generic_type; 11, 12; 11, 13; 12, identifier:Optional; 13, type_parameter; 13, 14; 14, type; 14, 15; 15, identifier:Callable; 16, None; 17, type; 17, 18; 18, generic_type; 18, 19; 18, 20; 19, identifier:Iterator; 20, type_parameter; 20, 21; 21, type; 21, 22; 22, identifier:Any; 23, block; 23, 24; 23, 26; 23, 122; 24, expression_statement; 24, 25; 25, comment; 26, for_statement; 26, 27; 26, 28; 26, 31; 27, identifier:statement; 28, subscript; 28, 29; 28, 30; 29, identifier:resp; 30, string:'results'; 31, block; 31, 32; 31, 38; 32, if_statement; 32, 33; 32, 36; 33, comparison_operator:not; 33, 34; 33, 35; 34, string:'series'; 35, identifier:statement; 36, block; 36, 37; 37, continue_statement; 38, for_statement; 38, 39; 38, 40; 38, 43; 39, identifier:series; 40, subscript; 40, 41; 40, 42; 41, identifier:statement; 42, string:'series'; 43, block; 43, 44; 44, if_statement; 44, 45; 44, 48; 44, 57; 44, 108; 45, comparison_operator:is; 45, 46; 45, 47; 46, identifier:parser; 47, None; 48, block; 48, 49; 49, return_statement; 49, 50; 50, generator_expression; 50, 51; 50, 52; 51, identifier:x; 52, for_in_clause; 52, 53; 52, 54; 53, identifier:x; 54, subscript; 54, 55; 54, 56; 55, identifier:series; 56, string:'values'; 57, elif_clause; 57, 58; 57, 68; 58, comparison_operator:in; 58, 59; 58, 60; 59, string:'meta'; 60, attribute; 60, 61; 60, 67; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:inspect; 64, identifier:signature; 65, argument_list; 65, 66; 66, identifier:parser; 67, identifier:parameters; 68, block; 68, 69; 68, 85; 68, 93; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:meta; 72, dictionary_comprehension; 72, 73; 72, 78; 72, 81; 73, pair; 73, 74; 73, 75; 74, identifier:k; 75, subscript; 75, 76; 75, 77; 76, identifier:series; 77, identifier:k; 78, for_in_clause; 78, 79; 78, 80; 79, identifier:k; 80, identifier:series; 81, if_clause; 81, 82; 82, comparison_operator:!=; 82, 83; 82, 84; 83, identifier:k; 84, string:'values'; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 90; 87, subscript; 87, 88; 87, 89; 88, identifier:meta; 89, string:'statement_id'; 90, subscript; 90, 91; 90, 92; 91, identifier:statement; 92, string:'statement_id'; 93, return_statement; 93, 94; 94, generator_expression; 94, 95; 94, 103; 95, call; 95, 96; 95, 97; 96, identifier:parser; 97, argument_list; 97, 98; 97, 100; 98, list_splat; 98, 99; 99, identifier:x; 100, keyword_argument; 100, 101; 100, 102; 101, identifier:meta; 102, identifier:meta; 103, for_in_clause; 103, 104; 103, 105; 104, identifier:x; 105, subscript; 105, 106; 105, 107; 106, identifier:series; 107, string:'values'; 108, else_clause; 108, 109; 109, block; 109, 110; 110, return_statement; 110, 111; 111, generator_expression; 111, 112; 111, 117; 112, call; 112, 113; 112, 114; 113, identifier:parser; 114, argument_list; 114, 115; 115, list_splat; 115, 116; 116, identifier:x; 117, for_in_clause; 117, 118; 117, 119; 118, identifier:x; 119, subscript; 119, 120; 119, 121; 120, identifier:series; 121, string:'values'; 122, return_statement; 122, 123; 123, call; 123, 124; 123, 125; 124, identifier:iter; 125, argument_list; 125, 126; 126, list:[]
def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: """Iterates a response JSON yielding data point by point. Can be used with both regular and chunked responses. By default, returns just a plain list of values representing each point, without column names, or other metadata. In case a specific format is needed, an optional ``parser`` argument can be passed. ``parser`` is a function/callable that takes data point values and, optionally, a ``meta`` parameter containing which takes a dictionary containing all or a subset of the following: ``{'columns', 'name', 'tags', 'statement_id'}``. Sample parser functions: .. code:: python # Function optional meta argument def parser(*x, meta): return dict(zip(meta['columns'], x)) # Namedtuple (callable) from collections import namedtuple parser = namedtuple('MyPoint', ['col1', 'col2', 'col3']) :param resp: Dictionary containing parsed JSON (output from InfluxDBClient.query) :param parser: Optional parser function/callable :return: Generator object """ for statement in resp['results']: if 'series' not in statement: continue for series in statement['series']: if parser is None: return (x for x in series['values']) elif 'meta' in inspect.signature(parser).parameters: meta = {k: series[k] for k in series if k != 'values'} meta['statement_id'] = statement['statement_id'] return (parser(*x, meta=meta) for x in series['values']) else: return (parser(*x) for x in series['values']) return iter([])
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 1, 13; 2, function_name:serialize; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:df; 5, identifier:measurement; 6, default_parameter; 6, 7; 6, 8; 7, identifier:tag_columns; 8, None; 9, dictionary_splat_pattern; 9, 10; 10, identifier:extra_tags; 11, type; 11, 12; 12, identifier:bytes; 13, block; 13, 14; 13, 16; 13, 17; 13, 27; 13, 44; 13, 53; 13, 68; 13, 69; 13, 73; 13, 77; 13, 94; 13, 185; 13, 205; 13, 222; 13, 223; 14, expression_statement; 14, 15; 15, comment; 16, comment; 17, if_statement; 17, 18; 17, 21; 18, comparison_operator:is; 18, 19; 18, 20; 19, identifier:measurement; 20, None; 21, block; 21, 22; 22, raise_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:ValueError; 25, argument_list; 25, 26; 26, string:"Missing 'measurement'"; 27, if_statement; 27, 28; 27, 38; 28, not_operator; 28, 29; 29, call; 29, 30; 29, 31; 30, identifier:isinstance; 31, argument_list; 31, 32; 31, 35; 32, attribute; 32, 33; 32, 34; 33, identifier:df; 34, identifier:index; 35, attribute; 35, 36; 35, 37; 36, identifier:pd; 37, identifier:DatetimeIndex; 38, block; 38, 39; 39, raise_statement; 39, 40; 40, call; 40, 41; 40, 42; 41, identifier:ValueError; 42, argument_list; 42, 43; 43, string:'DataFrame index is not DatetimeIndex'; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:tag_columns; 47, call; 47, 48; 47, 49; 48, identifier:set; 49, argument_list; 49, 50; 50, boolean_operator:or; 50, 51; 50, 52; 51, identifier:tag_columns; 52, list:[]; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:isnull; 56, call; 56, 57; 56, 64; 57, attribute; 57, 58; 57, 63; 58, call; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, identifier:df; 61, identifier:isnull; 62, argument_list; 63, identifier:any; 64, argument_list; 64, 65; 65, keyword_argument; 65, 66; 65, 67; 66, identifier:axis; 67, integer:1; 68, comment; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:tags; 72, list:[]; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:fields; 76, list:[]; 77, for_statement; 77, 78; 77, 81; 77, 86; 78, pattern_list; 78, 79; 78, 80; 79, identifier:k; 80, identifier:v; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:extra_tags; 84, identifier:items; 85, argument_list; 86, block; 86, 87; 87, expression_statement; 87, 88; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:tags; 91, identifier:append; 92, argument_list; 92, 93; 93, string:f"{k}={escape(v, key_escape)}"; 94, for_statement; 94, 95; 94, 100; 94, 110; 95, pattern_list; 95, 96; 95, 97; 96, identifier:i; 97, tuple_pattern; 97, 98; 97, 99; 98, identifier:k; 99, identifier:v; 100, call; 100, 101; 100, 102; 101, identifier:enumerate; 102, argument_list; 102, 103; 103, call; 103, 104; 103, 109; 104, attribute; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:df; 107, identifier:dtypes; 108, identifier:items; 109, argument_list; 110, block; 110, 111; 110, 120; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:k; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:k; 117, identifier:translate; 118, argument_list; 118, 119; 119, identifier:key_escape; 120, if_statement; 120, 121; 120, 124; 120, 132; 120, 150; 120, 172; 121, comparison_operator:in; 121, 122; 121, 123; 122, identifier:k; 123, identifier:tag_columns; 124, block; 124, 125; 125, expression_statement; 125, 126; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:tags; 129, identifier:append; 130, argument_list; 130, 131; 131, string:f"{k}={{p[{i+1}]}}"; 132, elif_clause; 132, 133; 132, 142; 133, call; 133, 134; 133, 135; 134, identifier:issubclass; 135, argument_list; 135, 136; 135, 139; 136, attribute; 136, 137; 136, 138; 137, identifier:v; 138, identifier:type; 139, attribute; 139, 140; 139, 141; 140, identifier:np; 141, identifier:integer; 142, block; 142, 143; 143, expression_statement; 143, 144; 144, call; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:fields; 147, identifier:append; 148, argument_list; 148, 149; 149, string:f"{k}={{p[{i+1}]}}i"; 150, elif_clause; 150, 151; 150, 164; 151, call; 151, 152; 151, 153; 152, identifier:issubclass; 153, argument_list; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:v; 156, identifier:type; 157, tuple; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:np; 160, identifier:float; 161, attribute; 161, 162; 161, 163; 162, identifier:np; 163, identifier:bool_; 164, block; 164, 165; 165, expression_statement; 165, 166; 166, call; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:fields; 169, identifier:append; 170, argument_list; 170, 171; 171, string:f"{k}={{p[{i+1}]}}"; 172, else_clause; 172, 173; 172, 174; 172, 175; 172, 176; 172, 177; 173, comment; 174, comment; 175, comment; 176, comment; 177, block; 177, 178; 178, expression_statement; 178, 179; 179, call; 179, 180; 179, 183; 180, attribute; 180, 181; 180, 182; 181, identifier:fields; 182, identifier:append; 183, argument_list; 183, 184; 184, string:f"{k}=\"{{p[{i+1}]}}\""; 185, expression_statement; 185, 186; 186, assignment; 186, 187; 186, 188; 187, identifier:fmt; 188, tuple; 188, 189; 188, 190; 188, 191; 188, 197; 188, 198; 188, 204; 189, string:f'{measurement}'; 190, string:f'{"," if tags else ""}'; 191, call; 191, 192; 191, 195; 192, attribute; 192, 193; 192, 194; 193, string:','; 194, identifier:join; 195, argument_list; 195, 196; 196, identifier:tags; 197, string:' '; 198, call; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, string:','; 201, identifier:join; 202, argument_list; 202, 203; 203, identifier:fields; 204, string:' {p[0].value}'; 205, expression_statement; 205, 206; 206, assignment; 206, 207; 206, 208; 207, identifier:f; 208, call; 208, 209; 208, 210; 209, identifier:eval; 210, argument_list; 210, 211; 211, call; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, string:"lambda p: f'{}'"; 214, identifier:format; 215, argument_list; 215, 216; 216, call; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, string:''; 219, identifier:join; 220, argument_list; 220, 221; 221, identifier:fmt; 222, comment; 223, if_statement; 223, 224; 223, 229; 223, 299; 224, call; 224, 225; 224, 228; 225, attribute; 225, 226; 225, 227; 226, identifier:isnull; 227, identifier:any; 228, argument_list; 229, block; 229, 230; 229, 244; 229, 251; 229, 283; 230, expression_statement; 230, 231; 231, assignment; 231, 232; 231, 233; 232, identifier:lp; 233, call; 233, 234; 233, 235; 234, identifier:map; 235, argument_list; 235, 236; 235, 237; 236, identifier:f; 237, call; 237, 238; 237, 239; 238, identifier:_itertuples; 239, argument_list; 239, 240; 240, subscript; 240, 241; 240, 242; 241, identifier:df; 242, unary_operator:~; 242, 243; 243, identifier:isnull; 244, expression_statement; 244, 245; 245, assignment; 245, 246; 245, 247; 246, identifier:rep; 247, call; 247, 248; 247, 249; 248, identifier:_replace; 249, argument_list; 249, 250; 250, identifier:df; 251, expression_statement; 251, 252; 252, assignment; 252, 253; 252, 254; 253, identifier:lp_nan; 254, generator_expression; 254, 255; 254, 275; 255, call; 255, 256; 255, 257; 256, identifier:reduce; 257, argument_list; 257, 258; 257, 270; 257, 271; 258, lambda; 258, 259; 258, 262; 259, lambda_parameters; 259, 260; 259, 261; 260, identifier:a; 261, identifier:b; 262, call; 262, 263; 262, 266; 263, attribute; 263, 264; 263, 265; 264, identifier:re; 265, identifier:sub; 266, argument_list; 266, 267; 266, 269; 267, list_splat; 267, 268; 268, identifier:b; 269, identifier:a; 270, identifier:rep; 271, call; 271, 272; 271, 273; 272, identifier:f; 273, argument_list; 273, 274; 274, identifier:p; 275, for_in_clause; 275, 276; 275, 277; 276, identifier:p; 277, call; 277, 278; 277, 279; 278, identifier:_itertuples; 279, argument_list; 279, 280; 280, subscript; 280, 281; 280, 282; 281, identifier:df; 282, identifier:isnull; 283, return_statement; 283, 284; 284, call; 284, 285; 284, 297; 285, attribute; 285, 286; 285, 296; 286, call; 286, 287; 286, 290; 287, attribute; 287, 288; 287, 289; 288, string:'\n'; 289, identifier:join; 290, argument_list; 290, 291; 291, call; 291, 292; 291, 293; 292, identifier:chain; 293, argument_list; 293, 294; 293, 295; 294, identifier:lp; 295, identifier:lp_nan; 296, identifier:encode; 297, argument_list; 297, 298; 298, string:'utf-8'; 299, else_clause; 299, 300; 300, block; 300, 301; 301, return_statement; 301, 302; 302, call; 302, 303; 302, 318; 303, attribute; 303, 304; 303, 317; 304, call; 304, 305; 304, 308; 305, attribute; 305, 306; 305, 307; 306, string:'\n'; 307, identifier:join; 308, argument_list; 308, 309; 309, call; 309, 310; 309, 311; 310, identifier:map; 311, argument_list; 311, 312; 311, 313; 312, identifier:f; 313, call; 313, 314; 313, 315; 314, identifier:_itertuples; 315, argument_list; 315, 316; 316, identifier:df; 317, identifier:encode; 318, argument_list; 318, 319; 319, string:'utf-8'
def serialize(df, measurement, tag_columns=None, **extra_tags) -> bytes: """Converts a Pandas DataFrame into line protocol format""" # Pre-processing if measurement is None: raise ValueError("Missing 'measurement'") if not isinstance(df.index, pd.DatetimeIndex): raise ValueError('DataFrame index is not DatetimeIndex') tag_columns = set(tag_columns or []) isnull = df.isnull().any(axis=1) # Make parser function tags = [] fields = [] for k, v in extra_tags.items(): tags.append(f"{k}={escape(v, key_escape)}") for i, (k, v) in enumerate(df.dtypes.items()): k = k.translate(key_escape) if k in tag_columns: tags.append(f"{k}={{p[{i+1}]}}") elif issubclass(v.type, np.integer): fields.append(f"{k}={{p[{i+1}]}}i") elif issubclass(v.type, (np.float, np.bool_)): fields.append(f"{k}={{p[{i+1}]}}") else: # String escaping is skipped for performance reasons # Strings containing double-quotes can cause strange write errors # and should be sanitized by the user. # e.g., df[k] = df[k].astype('str').str.translate(str_escape) fields.append(f"{k}=\"{{p[{i+1}]}}\"") fmt = (f'{measurement}', f'{"," if tags else ""}', ','.join(tags), ' ', ','.join(fields), ' {p[0].value}') f = eval("lambda p: f'{}'".format(''.join(fmt))) # Map/concat if isnull.any(): lp = map(f, _itertuples(df[~isnull])) rep = _replace(df) lp_nan = (reduce(lambda a, b: re.sub(*b, a), rep, f(p)) for p in _itertuples(df[isnull])) return '\n'.join(chain(lp, lp_nan)).encode('utf-8') else: return '\n'.join(map(f, _itertuples(df))).encode('utf-8')
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:get_my_feed; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:limit; 7, integer:150; 8, default_parameter; 8, 9; 8, 10; 9, identifier:offset; 10, integer:20; 11, default_parameter; 11, 12; 11, 13; 12, identifier:sort; 13, string:"updated"; 14, default_parameter; 14, 15; 14, 16; 15, identifier:nid; 16, None; 17, block; 17, 18; 17, 20; 17, 48; 18, expression_statement; 18, 19; 19, comment; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:r; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:self; 26, identifier:request; 27, argument_list; 27, 28; 27, 31; 27, 34; 28, keyword_argument; 28, 29; 28, 30; 29, identifier:method; 30, string:"network.get_my_feed"; 31, keyword_argument; 31, 32; 31, 33; 32, identifier:nid; 33, identifier:nid; 34, keyword_argument; 34, 35; 34, 36; 35, identifier:data; 36, call; 36, 37; 36, 38; 37, identifier:dict; 38, argument_list; 38, 39; 38, 42; 38, 45; 39, keyword_argument; 39, 40; 39, 41; 40, identifier:limit; 41, identifier:limit; 42, keyword_argument; 42, 43; 42, 44; 43, identifier:offset; 44, identifier:offset; 45, keyword_argument; 45, 46; 45, 47; 46, identifier:sort; 47, identifier:sort; 48, return_statement; 48, 49; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:self; 52, identifier:_handle_error; 53, argument_list; 53, 54; 53, 55; 54, identifier:r; 55, string:"Could not retrieve your feed."
def get_my_feed(self, limit=150, offset=20, sort="updated", nid=None): """Get my feed :type limit: int :param limit: Number of posts from feed to get, starting from ``offset`` :type offset: int :param offset: Offset starting from bottom of feed :type sort: str :param sort: How to sort feed that will be retrieved; only current known value is "updated" :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class """ r = self.request( method="network.get_my_feed", nid=nid, data=dict( limit=limit, offset=offset, sort=sort ) ) return self._handle_error(r, "Could not retrieve your feed.")
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 23; 2, function_name:filter_feed; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:updated; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:following; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:folder; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:filter_folder; 16, string:""; 17, default_parameter; 17, 18; 17, 19; 18, identifier:sort; 19, string:"updated"; 20, default_parameter; 20, 21; 20, 22; 21, identifier:nid; 22, None; 23, block; 23, 24; 23, 26; 23, 36; 23, 41; 23, 79; 23, 103; 24, expression_statement; 24, 25; 25, comment; 26, assert_statement; 26, 27; 27, comparison_operator:==; 27, 28; 27, 35; 28, call; 28, 29; 28, 30; 29, identifier:sum; 30, argument_list; 30, 31; 31, list:[updated, following, folder]; 31, 32; 31, 33; 31, 34; 32, identifier:updated; 33, identifier:following; 34, identifier:folder; 35, integer:1; 36, if_statement; 36, 37; 36, 38; 37, identifier:folder; 38, block; 38, 39; 39, assert_statement; 39, 40; 40, identifier:filter_folder; 41, if_statement; 41, 42; 41, 43; 41, 53; 41, 65; 42, identifier:updated; 43, block; 43, 44; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:filter_type; 47, call; 47, 48; 47, 49; 48, identifier:dict; 49, argument_list; 49, 50; 50, keyword_argument; 50, 51; 50, 52; 51, identifier:updated; 52, integer:1; 53, elif_clause; 53, 54; 53, 55; 54, identifier:following; 55, block; 55, 56; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:filter_type; 59, call; 59, 60; 59, 61; 60, identifier:dict; 61, argument_list; 61, 62; 62, keyword_argument; 62, 63; 62, 64; 63, identifier:following; 64, integer:1; 65, else_clause; 65, 66; 66, block; 66, 67; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:filter_type; 70, call; 70, 71; 70, 72; 71, identifier:dict; 72, argument_list; 72, 73; 72, 76; 73, keyword_argument; 73, 74; 73, 75; 74, identifier:folder; 75, integer:1; 76, keyword_argument; 76, 77; 76, 78; 77, identifier:filter_folder; 78, identifier:filter_folder; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:r; 82, call; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:self; 85, identifier:request; 86, argument_list; 86, 87; 86, 90; 86, 93; 87, keyword_argument; 87, 88; 87, 89; 88, identifier:nid; 89, identifier:nid; 90, keyword_argument; 90, 91; 90, 92; 91, identifier:method; 92, string:"network.filter_feed"; 93, keyword_argument; 93, 94; 93, 95; 94, identifier:data; 95, call; 95, 96; 95, 97; 96, identifier:dict; 97, argument_list; 97, 98; 97, 101; 98, keyword_argument; 98, 99; 98, 100; 99, identifier:sort; 100, identifier:sort; 101, dictionary_splat; 101, 102; 102, identifier:filter_type; 103, return_statement; 103, 104; 104, call; 104, 105; 104, 108; 105, attribute; 105, 106; 105, 107; 106, identifier:self; 107, identifier:_handle_error; 108, argument_list; 108, 109; 108, 110; 109, identifier:r; 110, string:"Could not retrieve filtered feed."
def filter_feed(self, updated=False, following=False, folder=False, filter_folder="", sort="updated", nid=None): """Get filtered feed Only one filter type (updated, following, folder) is possible. :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class :type sort: str :param sort: How to sort feed that will be retrieved; only current known value is "updated" :type updated: bool :param updated: Set to filter through only posts which have been updated since you last read them :type following: bool :param following: Set to filter through only posts which you are following :type folder: bool :param folder: Set to filter through only posts which are in the provided ``filter_folder`` :type filter_folder: str :param filter_folder: Name of folder to show posts from; required only if ``folder`` is set """ assert sum([updated, following, folder]) == 1 if folder: assert filter_folder if updated: filter_type = dict(updated=1) elif following: filter_type = dict(following=1) else: filter_type = dict(folder=1, filter_folder=filter_folder) r = self.request( nid=nid, method="network.filter_feed", data=dict( sort=sort, **filter_type ) ) return self._handle_error(r, "Could not retrieve filtered feed.")
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:get_dataset; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:dataset; 6, block; 6, 7; 6, 9; 6, 10; 6, 14; 6, 22; 6, 225; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:success; 13, True; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:dataset_path; 17, binary_operator:+; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:self; 20, identifier:base_dataset_path; 21, identifier:dataset; 22, if_statement; 22, 23; 22, 28; 22, 29; 23, not_operator; 23, 24; 24, call; 24, 25; 24, 26; 25, identifier:isdir; 26, argument_list; 26, 27; 27, identifier:dataset_path; 28, comment; 29, block; 29, 30; 29, 34; 29, 193; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:was_error; 33, False; 34, for_statement; 34, 35; 34, 36; 34, 40; 34, 41; 35, identifier:iteration; 36, call; 36, 37; 36, 38; 37, identifier:range; 38, argument_list; 38, 39; 39, integer:5; 40, comment; 41, block; 41, 42; 42, if_statement; 42, 43; 42, 50; 43, boolean_operator:or; 43, 44; 43, 47; 44, comparison_operator:==; 44, 45; 44, 46; 45, identifier:iteration; 46, integer:0; 47, comparison_operator:is; 47, 48; 47, 49; 48, identifier:was_error; 49, True; 50, block; 50, 51; 50, 57; 50, 58; 50, 123; 50, 124; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:zip_path; 54, binary_operator:+; 54, 55; 54, 56; 55, identifier:dataset_path; 56, string:".zip"; 57, comment; 58, if_statement; 58, 59; 58, 64; 59, not_operator; 59, 60; 60, call; 60, 61; 60, 62; 61, identifier:isfile; 62, argument_list; 62, 63; 63, identifier:zip_path; 64, block; 64, 65; 65, try_statement; 65, 66; 65, 104; 66, block; 66, 67; 67, with_statement; 67, 68; 67, 88; 68, with_clause; 68, 69; 69, with_item; 69, 70; 70, as_pattern; 70, 71; 70, 86; 71, call; 71, 72; 71, 73; 72, identifier:DLProgress; 73, argument_list; 73, 74; 73, 77; 73, 80; 73, 83; 74, keyword_argument; 74, 75; 74, 76; 75, identifier:unit; 76, string:'B'; 77, keyword_argument; 77, 78; 77, 79; 78, identifier:unit_scale; 79, True; 80, keyword_argument; 80, 81; 80, 82; 81, identifier:miniters; 82, integer:1; 83, keyword_argument; 83, 84; 83, 85; 84, identifier:desc; 85, identifier:dataset; 86, as_pattern_target; 86, 87; 87, identifier:pbar; 88, block; 88, 89; 89, expression_statement; 89, 90; 90, call; 90, 91; 90, 92; 91, identifier:urlretrieve; 92, argument_list; 92, 93; 92, 100; 92, 101; 93, subscript; 93, 94; 93, 99; 94, subscript; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:self; 97, identifier:datasets; 98, identifier:dataset; 99, string:"url"; 100, identifier:zip_path; 101, attribute; 101, 102; 101, 103; 102, identifier:pbar; 103, identifier:hook; 104, except_clause; 104, 105; 104, 109; 105, as_pattern; 105, 106; 105, 107; 106, identifier:Exception; 107, as_pattern_target; 107, 108; 108, identifier:ex; 109, block; 109, 110; 109, 119; 110, expression_statement; 110, 111; 111, call; 111, 112; 111, 113; 112, identifier:print; 113, argument_list; 113, 114; 114, binary_operator:%; 114, 115; 114, 116; 115, string:"Error downloading %s: %s"; 116, tuple; 116, 117; 116, 118; 117, identifier:dataset; 118, identifier:ex; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:was_error; 122, True; 123, comment; 124, if_statement; 124, 125; 124, 130; 125, not_operator; 125, 126; 126, call; 126, 127; 126, 128; 127, identifier:isdir; 128, argument_list; 128, 129; 129, identifier:dataset_path; 130, block; 130, 131; 131, try_statement; 131, 132; 131, 161; 132, block; 132, 133; 133, with_statement; 133, 134; 133, 145; 134, with_clause; 134, 135; 135, with_item; 135, 136; 136, as_pattern; 136, 137; 136, 143; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:zipfile; 140, identifier:ZipFile; 141, argument_list; 141, 142; 142, identifier:zip_path; 143, as_pattern_target; 143, 144; 144, identifier:zip_archive; 145, block; 145, 146; 145, 155; 146, expression_statement; 146, 147; 147, call; 147, 148; 147, 151; 148, attribute; 148, 149; 148, 150; 149, identifier:zip_archive; 150, identifier:extractall; 151, argument_list; 151, 152; 152, keyword_argument; 152, 153; 152, 154; 153, identifier:path; 154, identifier:dataset_path; 155, expression_statement; 155, 156; 156, call; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:zip_archive; 159, identifier:close; 160, argument_list; 161, except_clause; 161, 162; 161, 166; 162, as_pattern; 162, 163; 162, 164; 163, identifier:Exception; 164, as_pattern_target; 164, 165; 165, identifier:ex; 166, block; 166, 167; 166, 176; 166, 177; 166, 178; 166, 189; 167, expression_statement; 167, 168; 168, call; 168, 169; 168, 170; 169, identifier:print; 170, argument_list; 170, 171; 171, binary_operator:%; 171, 172; 171, 173; 172, string:"Error unzipping %s: %s"; 173, tuple; 173, 174; 173, 175; 174, identifier:zip_path; 175, identifier:ex; 176, comment; 177, comment; 178, try_statement; 178, 179; 178, 185; 179, block; 179, 180; 180, expression_statement; 180, 181; 181, call; 181, 182; 181, 183; 182, identifier:remove; 183, argument_list; 183, 184; 184, identifier:zip_path; 185, except_clause; 185, 186; 185, 187; 186, identifier:FileNotFoundError; 187, block; 187, 188; 188, pass_statement; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 192; 191, identifier:was_error; 192, True; 193, if_statement; 193, 194; 193, 195; 194, identifier:was_error; 195, block; 195, 196; 195, 201; 195, 214; 195, 221; 196, expression_statement; 196, 197; 197, call; 197, 198; 197, 199; 198, identifier:print; 199, argument_list; 199, 200; 200, string:"\nThis recognizer is trained by the CASIA handwriting database."; 201, expression_statement; 201, 202; 202, call; 202, 203; 202, 204; 203, identifier:print; 204, argument_list; 204, 205; 205, binary_operator:%; 205, 206; 205, 207; 206, string:"If the download doesn't work, you can get the files at %s"; 207, subscript; 207, 208; 207, 213; 208, subscript; 208, 209; 208, 212; 209, attribute; 209, 210; 209, 211; 210, identifier:self; 211, identifier:datasets; 212, identifier:dataset; 213, string:"url"; 214, expression_statement; 214, 215; 215, call; 215, 216; 215, 217; 216, identifier:print; 217, argument_list; 217, 218; 218, concatenated_string; 218, 219; 218, 220; 219, string:"If you have download problems, "; 220, string:"wget may be effective at downloading because of download resuming."; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 224; 223, identifier:success; 224, False; 225, return_statement; 225, 226; 226, identifier:success
def get_dataset(self, dataset): """ Checks to see if the dataset is present. If not, it downloads and unzips it. """ # If the dataset is present, no need to download anything. success = True dataset_path = self.base_dataset_path + dataset if not isdir(dataset_path): # Try 5 times to download. The download page is unreliable, so we need a few tries. was_error = False for iteration in range(5): # Guard against trying again if successful if iteration == 0 or was_error is True: zip_path = dataset_path + ".zip" # Download zip files if they're not there if not isfile(zip_path): try: with DLProgress(unit='B', unit_scale=True, miniters=1, desc=dataset) as pbar: urlretrieve(self.datasets[dataset]["url"], zip_path, pbar.hook) except Exception as ex: print("Error downloading %s: %s" % (dataset, ex)) was_error = True # Unzip the data files if not isdir(dataset_path): try: with zipfile.ZipFile(zip_path) as zip_archive: zip_archive.extractall(path=dataset_path) zip_archive.close() except Exception as ex: print("Error unzipping %s: %s" % (zip_path, ex)) # Usually the error is caused by a bad zip file. # Delete it so the program will try to download it again. try: remove(zip_path) except FileNotFoundError: pass was_error = True if was_error: print("\nThis recognizer is trained by the CASIA handwriting database.") print("If the download doesn't work, you can get the files at %s" % self.datasets[dataset]["url"]) print("If you have download problems, " "wget may be effective at downloading because of download resuming.") success = False return success
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 32; 2, function_name:install; 3, parameters; 3, 4; 3, 7; 3, 27; 3, 30; 4, default_parameter; 4, 5; 4, 6; 5, identifier:verbose; 6, True; 7, default_parameter; 7, 8; 7, 9; 8, identifier:verbose_destination; 9, conditional_expression:if; 9, 10; 9, 17; 9, 24; 10, call; 10, 11; 10, 16; 11, attribute; 11, 12; 11, 15; 12, attribute; 12, 13; 12, 14; 13, identifier:sys; 14, identifier:__stderr__; 15, identifier:fileno; 16, argument_list; 17, call; 17, 18; 17, 19; 18, identifier:hasattr; 19, argument_list; 19, 20; 19, 23; 20, attribute; 20, 21; 20, 22; 21, identifier:sys; 22, identifier:__stderr__; 23, string:'fileno'; 24, attribute; 24, 25; 24, 26; 25, identifier:sys; 26, identifier:__stderr__; 27, default_parameter; 27, 28; 27, 29; 28, identifier:strict; 29, True; 30, dictionary_splat_pattern; 30, 31; 31, identifier:kwargs; 32, block; 32, 33; 32, 35; 32, 36; 32, 38; 32, 79; 32, 87; 32, 95; 32, 96; 33, expression_statement; 33, 34; 34, comment; 35, comment; 36, global_statement; 36, 37; 37, identifier:_MANHOLE; 38, with_statement; 38, 39; 38, 42; 39, with_clause; 39, 40; 40, with_item; 40, 41; 41, identifier:_LOCK; 42, block; 42, 43; 43, if_statement; 43, 44; 43, 47; 43, 54; 44, comparison_operator:is; 44, 45; 44, 46; 45, identifier:_MANHOLE; 46, None; 47, block; 47, 48; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:_MANHOLE; 51, call; 51, 52; 51, 53; 52, identifier:Manhole; 53, argument_list; 54, else_clause; 54, 55; 55, block; 55, 56; 56, if_statement; 56, 57; 56, 58; 56, 64; 57, identifier:strict; 58, block; 58, 59; 59, raise_statement; 59, 60; 60, call; 60, 61; 60, 62; 61, identifier:AlreadyInstalled; 62, argument_list; 62, 63; 63, string:"Manhole already installed!"; 64, else_clause; 64, 65; 65, block; 65, 66; 65, 72; 65, 78; 66, expression_statement; 66, 67; 67, call; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:_LOG; 70, identifier:release; 71, argument_list; 72, expression_statement; 72, 73; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:_MANHOLE; 76, identifier:release; 77, argument_list; 78, comment; 79, expression_statement; 79, 80; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:_LOG; 83, identifier:configure; 84, argument_list; 84, 85; 84, 86; 85, identifier:verbose; 86, identifier:verbose_destination; 87, expression_statement; 87, 88; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:_MANHOLE; 91, identifier:configure; 92, argument_list; 92, 93; 93, dictionary_splat; 93, 94; 94, identifier:kwargs; 95, comment; 96, return_statement; 96, 97; 97, identifier:_MANHOLE
def install(verbose=True, verbose_destination=sys.__stderr__.fileno() if hasattr(sys.__stderr__, 'fileno') else sys.__stderr__, strict=True, **kwargs): """ Installs the manhole. Args: verbose (bool): Set it to ``False`` to squelch the logging. verbose_destination (file descriptor or handle): Destination for verbose messages. Default is unbuffered stderr (stderr ``2`` file descriptor). patch_fork (bool): Set it to ``False`` if you don't want your ``os.fork`` and ``os.forkpy`` monkeypatched activate_on (int or signal name): set to ``"USR1"``, ``"USR2"`` or some other signal name, or a number if you want the Manhole thread to start when this signal is sent. This is desireable in case you don't want the thread active all the time. oneshot_on (int or signal name): Set to ``"USR1"``, ``"USR2"`` or some other signal name, or a number if you want the Manhole to listen for connection in the signal handler. This is desireable in case you don't want threads at all. thread (bool): Start the always-on ManholeThread. Default: ``True``. Automatically switched to ``False`` if ``oneshort_on`` or ``activate_on`` are used. sigmask (list of ints or signal names): Will set the signal mask to the given list (using ``signalfd.sigprocmask``). No action is done if ``signalfd`` is not importable. **NOTE**: This is done so that the Manhole thread doesn't *steal* any signals; Normally that is fine because Python will force all the signal handling to be run in the main thread but signalfd doesn't. socket_path (str): Use a specific path for the unix domain socket (instead of ``/tmp/manhole-<pid>``). This disables ``patch_fork`` as children cannot reuse the same path. reinstall_delay (float): Delay the unix domain socket creation *reinstall_delay* seconds. This alleviates cleanup failures when using fork+exec patterns. locals (dict): Names to add to manhole interactive shell locals. daemon_connection (bool): The connection thread is daemonic (dies on app exit). Default: ``False``. redirect_stderr (bool): Redirect output from stderr to manhole console. Default: ``True``. connection_handler (function): Connection handler to use. Use ``"exec"`` for simple implementation without output redirection or your own function. (warning: this is for advanced users). Default: ``"repl"``. """ # pylint: disable=W0603 global _MANHOLE with _LOCK: if _MANHOLE is None: _MANHOLE = Manhole() else: if strict: raise AlreadyInstalled("Manhole already installed!") else: _LOG.release() _MANHOLE.release() # Threads might be started here _LOG.configure(verbose, verbose_destination) _MANHOLE.configure(**kwargs) # Threads might be started here return _MANHOLE
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 38; 2, function_name:update; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 3, 29; 3, 32; 3, 35; 4, comment; 5, identifier:self; 6, identifier:alert_condition_nrql_id; 7, identifier:policy_id; 8, default_parameter; 8, 9; 8, 10; 9, identifier:name; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:threshold_type; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:query; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:since_value; 19, None; 20, default_parameter; 20, 21; 20, 22; 21, identifier:terms; 22, None; 23, default_parameter; 23, 24; 23, 25; 24, identifier:expected_groups; 25, None; 26, default_parameter; 26, 27; 26, 28; 27, identifier:value_function; 28, None; 29, default_parameter; 29, 30; 29, 31; 30, identifier:runbook_url; 31, None; 32, default_parameter; 32, 33; 32, 34; 33, identifier:ignore_overlap; 34, None; 35, default_parameter; 35, 36; 35, 37; 36, identifier:enabled; 37, True; 38, block; 38, 39; 38, 41; 38, 50; 38, 54; 38, 75; 38, 93; 38, 147; 38, 167; 38, 195; 38, 223; 38, 251; 38, 279; 38, 363; 39, expression_statement; 39, 40; 40, comment; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:conditions_nrql_dict; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:self; 47, identifier:list; 48, argument_list; 48, 49; 49, identifier:policy_id; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:target_condition_nrql; 53, None; 54, for_statement; 54, 55; 54, 56; 54, 59; 55, identifier:condition; 56, subscript; 56, 57; 56, 58; 57, identifier:conditions_nrql_dict; 58, string:'nrql_conditions'; 59, block; 59, 60; 60, if_statement; 60, 61; 60, 69; 61, comparison_operator:==; 61, 62; 61, 68; 62, call; 62, 63; 62, 64; 63, identifier:int; 64, argument_list; 64, 65; 65, subscript; 65, 66; 65, 67; 66, identifier:condition; 67, string:'id'; 68, identifier:alert_condition_nrql_id; 69, block; 69, 70; 69, 74; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:target_condition_nrql; 73, identifier:condition; 74, break_statement; 75, if_statement; 75, 76; 75, 79; 76, comparison_operator:is; 76, 77; 76, 78; 77, identifier:target_condition_nrql; 78, None; 79, block; 79, 80; 80, raise_statement; 80, 81; 81, call; 81, 82; 81, 83; 82, identifier:NoEntityException; 83, argument_list; 83, 84; 84, call; 84, 85; 84, 90; 85, attribute; 85, 86; 85, 89; 86, concatenated_string; 86, 87; 86, 88; 87, string:'Target alert condition nrql is not included in that policy.'; 88, string:'policy_id: {}, alert_condition_nrql_id {}'; 89, identifier:format; 90, argument_list; 90, 91; 90, 92; 91, identifier:policy_id; 92, identifier:alert_condition_nrql_id; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:data; 96, dictionary; 96, 97; 97, pair; 97, 98; 97, 99; 98, string:'nrql_condition'; 99, dictionary; 99, 100; 99, 107; 99, 112; 99, 119; 99, 126; 100, pair; 100, 101; 100, 102; 101, string:'type'; 102, boolean_operator:or; 102, 103; 102, 104; 103, identifier:threshold_type; 104, subscript; 104, 105; 104, 106; 105, identifier:target_condition_nrql; 106, string:'type'; 107, pair; 107, 108; 107, 109; 108, string:'enabled'; 109, subscript; 109, 110; 109, 111; 110, identifier:target_condition_nrql; 111, string:'enabled'; 112, pair; 112, 113; 112, 114; 113, string:'name'; 114, boolean_operator:or; 114, 115; 114, 116; 115, identifier:name; 116, subscript; 116, 117; 116, 118; 117, identifier:target_condition_nrql; 118, string:'name'; 119, pair; 119, 120; 119, 121; 120, string:'terms'; 121, boolean_operator:or; 121, 122; 121, 123; 122, identifier:terms; 123, subscript; 123, 124; 123, 125; 124, identifier:target_condition_nrql; 125, string:'terms'; 126, pair; 126, 127; 126, 128; 127, string:'nrql'; 128, dictionary; 128, 129; 128, 138; 129, pair; 129, 130; 129, 131; 130, string:'query'; 131, boolean_operator:or; 131, 132; 131, 133; 132, identifier:query; 133, subscript; 133, 134; 133, 137; 134, subscript; 134, 135; 134, 136; 135, identifier:target_condition_nrql; 136, string:'nrql'; 137, string:'query'; 138, pair; 138, 139; 138, 140; 139, string:'since_value'; 140, boolean_operator:or; 140, 141; 140, 142; 141, identifier:since_value; 142, subscript; 142, 143; 142, 146; 143, subscript; 143, 144; 143, 145; 144, identifier:target_condition_nrql; 145, string:'nrql'; 146, string:'since_value'; 147, if_statement; 147, 148; 147, 151; 148, comparison_operator:is; 148, 149; 148, 150; 149, identifier:enabled; 150, None; 151, block; 151, 152; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 159; 154, subscript; 154, 155; 154, 158; 155, subscript; 155, 156; 155, 157; 156, identifier:data; 157, string:'nrql_condition'; 158, string:'enabled'; 159, call; 159, 160; 159, 166; 160, attribute; 160, 161; 160, 165; 161, call; 161, 162; 161, 163; 162, identifier:str; 163, argument_list; 163, 164; 164, identifier:enabled; 165, identifier:lower; 166, argument_list; 167, if_statement; 167, 168; 167, 171; 167, 180; 168, comparison_operator:is; 168, 169; 168, 170; 169, identifier:runbook_url; 170, None; 171, block; 171, 172; 172, expression_statement; 172, 173; 173, assignment; 173, 174; 173, 179; 174, subscript; 174, 175; 174, 178; 175, subscript; 175, 176; 175, 177; 176, identifier:data; 177, string:'nrql_condition'; 178, string:'runbook_url'; 179, identifier:runbook_url; 180, elif_clause; 180, 181; 180, 184; 181, comparison_operator:in; 181, 182; 181, 183; 182, string:'runbook_url'; 183, identifier:target_condition_nrql; 184, block; 184, 185; 185, expression_statement; 185, 186; 186, assignment; 186, 187; 186, 192; 187, subscript; 187, 188; 187, 191; 188, subscript; 188, 189; 188, 190; 189, identifier:data; 190, string:'nrql_condition'; 191, string:'runbook_url'; 192, subscript; 192, 193; 192, 194; 193, identifier:target_condition_nrql; 194, string:'runbook_url'; 195, if_statement; 195, 196; 195, 199; 195, 208; 196, comparison_operator:is; 196, 197; 196, 198; 197, identifier:expected_groups; 198, None; 199, block; 199, 200; 200, expression_statement; 200, 201; 201, assignment; 201, 202; 201, 207; 202, subscript; 202, 203; 202, 206; 203, subscript; 203, 204; 203, 205; 204, identifier:data; 205, string:'nrql_condition'; 206, string:'expected_groups'; 207, identifier:expected_groups; 208, elif_clause; 208, 209; 208, 212; 209, comparison_operator:in; 209, 210; 209, 211; 210, string:'expected_groups'; 211, identifier:target_condition_nrql; 212, block; 212, 213; 213, expression_statement; 213, 214; 214, assignment; 214, 215; 214, 220; 215, subscript; 215, 216; 215, 219; 216, subscript; 216, 217; 216, 218; 217, identifier:data; 218, string:'nrql_condition'; 219, string:'expected_groups'; 220, subscript; 220, 221; 220, 222; 221, identifier:target_condition_nrql; 222, string:'expected_groups'; 223, if_statement; 223, 224; 223, 227; 223, 236; 224, comparison_operator:is; 224, 225; 224, 226; 225, identifier:ignore_overlap; 226, None; 227, block; 227, 228; 228, expression_statement; 228, 229; 229, assignment; 229, 230; 229, 235; 230, subscript; 230, 231; 230, 234; 231, subscript; 231, 232; 231, 233; 232, identifier:data; 233, string:'nrql_condition'; 234, string:'ignore_overlap'; 235, identifier:ignore_overlap; 236, elif_clause; 236, 237; 236, 240; 237, comparison_operator:in; 237, 238; 237, 239; 238, string:'ignore_overlap'; 239, identifier:target_condition_nrql; 240, block; 240, 241; 241, expression_statement; 241, 242; 242, assignment; 242, 243; 242, 248; 243, subscript; 243, 244; 243, 247; 244, subscript; 244, 245; 244, 246; 245, identifier:data; 246, string:'nrql_condition'; 247, string:'ignore_overlap'; 248, subscript; 248, 249; 248, 250; 249, identifier:target_condition_nrql; 250, string:'ignore_overlap'; 251, if_statement; 251, 252; 251, 255; 251, 264; 252, comparison_operator:is; 252, 253; 252, 254; 253, identifier:value_function; 254, None; 255, block; 255, 256; 256, expression_statement; 256, 257; 257, assignment; 257, 258; 257, 263; 258, subscript; 258, 259; 258, 262; 259, subscript; 259, 260; 259, 261; 260, identifier:data; 261, string:'nrql_condition'; 262, string:'value_function'; 263, identifier:value_function; 264, elif_clause; 264, 265; 264, 268; 265, comparison_operator:in; 265, 266; 265, 267; 266, string:'value_function'; 267, identifier:target_condition_nrql; 268, block; 268, 269; 269, expression_statement; 269, 270; 270, assignment; 270, 271; 270, 276; 271, subscript; 271, 272; 271, 275; 272, subscript; 272, 273; 272, 274; 273, identifier:data; 274, string:'nrql_condition'; 275, string:'value_function'; 276, subscript; 276, 277; 276, 278; 277, identifier:target_condition_nrql; 278, string:'value_function'; 279, if_statement; 279, 280; 279, 287; 279, 320; 280, comparison_operator:==; 280, 281; 280, 286; 281, subscript; 281, 282; 281, 285; 282, subscript; 282, 283; 282, 284; 283, identifier:data; 284, string:'nrql_condition'; 285, string:'type'; 286, string:'static'; 287, block; 287, 288; 287, 300; 287, 310; 288, if_statement; 288, 289; 288, 294; 289, comparison_operator:not; 289, 290; 289, 291; 290, string:'value_function'; 291, subscript; 291, 292; 291, 293; 292, identifier:data; 293, string:'nrql_condition'; 294, block; 294, 295; 295, raise_statement; 295, 296; 296, call; 296, 297; 296, 298; 297, identifier:ConfigurationException; 298, argument_list; 298, 299; 299, string:'Alert is set as static but no value_function config specified'; 300, expression_statement; 300, 301; 301, call; 301, 302; 301, 307; 302, attribute; 302, 303; 302, 306; 303, subscript; 303, 304; 303, 305; 304, identifier:data; 305, string:'nrql_condition'; 306, identifier:pop; 307, argument_list; 307, 308; 307, 309; 308, string:'expected_groups'; 309, None; 310, expression_statement; 310, 311; 311, call; 311, 312; 311, 317; 312, attribute; 312, 313; 312, 316; 313, subscript; 313, 314; 313, 315; 314, identifier:data; 315, string:'nrql_condition'; 316, identifier:pop; 317, argument_list; 317, 318; 317, 319; 318, string:'ignore_overlap'; 319, None; 320, elif_clause; 320, 321; 320, 328; 321, comparison_operator:==; 321, 322; 321, 327; 322, subscript; 322, 323; 322, 326; 323, subscript; 323, 324; 323, 325; 324, identifier:data; 325, string:'nrql_condition'; 326, string:'type'; 327, string:'outlier'; 328, block; 328, 329; 328, 341; 328, 353; 329, if_statement; 329, 330; 329, 335; 330, comparison_operator:not; 330, 331; 330, 332; 331, string:'expected_groups'; 332, subscript; 332, 333; 332, 334; 333, identifier:data; 334, string:'nrql_condition'; 335, block; 335, 336; 336, raise_statement; 336, 337; 337, call; 337, 338; 337, 339; 338, identifier:ConfigurationException; 339, argument_list; 339, 340; 340, string:'Alert is set as outlier but expected_groups config is not specified'; 341, if_statement; 341, 342; 341, 347; 342, comparison_operator:not; 342, 343; 342, 344; 343, string:'ignore_overlap'; 344, subscript; 344, 345; 344, 346; 345, identifier:data; 346, string:'nrql_condition'; 347, block; 347, 348; 348, raise_statement; 348, 349; 349, call; 349, 350; 349, 351; 350, identifier:ConfigurationException; 351, argument_list; 351, 352; 352, string:'Alert is set as outlier but ignore_overlap config is not specified'; 353, expression_statement; 353, 354; 354, call; 354, 355; 354, 360; 355, attribute; 355, 356; 355, 359; 356, subscript; 356, 357; 356, 358; 357, identifier:data; 358, string:'nrql_condition'; 359, identifier:pop; 360, argument_list; 360, 361; 360, 362; 361, string:'value_function'; 362, None; 363, return_statement; 363, 364; 364, call; 364, 365; 364, 368; 365, attribute; 365, 366; 365, 367; 366, identifier:self; 367, identifier:_put; 368, argument_list; 368, 369; 368, 380; 368, 385; 369, keyword_argument; 369, 370; 369, 371; 370, identifier:url; 371, call; 371, 372; 371, 375; 372, attribute; 372, 373; 372, 374; 373, string:'{0}alerts_nrql_conditions/{1}.json'; 374, identifier:format; 375, argument_list; 375, 376; 375, 379; 376, attribute; 376, 377; 376, 378; 377, identifier:self; 378, identifier:URL; 379, identifier:alert_condition_nrql_id; 380, keyword_argument; 380, 381; 380, 382; 381, identifier:headers; 382, attribute; 382, 383; 382, 384; 383, identifier:self; 384, identifier:headers; 385, keyword_argument; 385, 386; 385, 387; 386, identifier:data; 387, identifier:data
def update( # noqa: C901 self, alert_condition_nrql_id, policy_id, name=None, threshold_type=None, query=None, since_value=None, terms=None, expected_groups=None, value_function=None, runbook_url=None, ignore_overlap=None, enabled=True): """ Updates any of the optional parameters of the alert condition nrql :type alert_condition_nrql_id: int :param alert_condition_nrql_id: Alerts condition NRQL id to update :type policy_id: int :param policy_id: Alert policy id where target alert condition belongs to :type condition_scope: str :param condition_scope: The scope of the condition, can be instance or application :type name: str :param name: The name of the alert :type threshold_type: str :param threshold_type: The tthreshold_typeype of the condition, can be static or outlier :type query: str :param query: nrql query for the alerts :type since_value: str :param since_value: since value for the alert :type terms: list[hash] :param terms: list of hashes containing threshold config for the alert :type expected_groups: int :param expected_groups: expected groups setting for outlier alerts :type value_function: str :param type: value function for static alerts :type runbook_url: str :param runbook_url: The url of the runbook :type ignore_overlap: bool :param ignore_overlap: Whether to ignore overlaps for outlier alerts :type enabled: bool :param enabled: Whether to enable that alert condition :rtype: dict :return: The JSON response of the API :raises: This will raise a :class:`NewRelicAPIServerException<newrelic_api.exceptions.NoEntityException>` if target alert condition is not included in target policy :raises: This will raise a :class:`ConfigurationException<newrelic_api.exceptions.ConfigurationException>` if metric is set as user_defined but user_defined config is not passed :: { "nrql_condition": { "name": "string", "runbook_url": "string", "enabled": "boolean", "expected_groups": "integer", "ignore_overlap": "boolean", "value_function": "string", "terms": [ { "duration": "string", "operator": "string", "priority": "string", "threshold": "string", "time_function": "string" } ], "nrql": { "query": "string", "since_value": "string" } } } """ conditions_nrql_dict = self.list(policy_id) target_condition_nrql = None for condition in conditions_nrql_dict['nrql_conditions']: if int(condition['id']) == alert_condition_nrql_id: target_condition_nrql = condition break if target_condition_nrql is None: raise NoEntityException( 'Target alert condition nrql is not included in that policy.' 'policy_id: {}, alert_condition_nrql_id {}'.format( policy_id, alert_condition_nrql_id ) ) data = { 'nrql_condition': { 'type': threshold_type or target_condition_nrql['type'], 'enabled': target_condition_nrql['enabled'], 'name': name or target_condition_nrql['name'], 'terms': terms or target_condition_nrql['terms'], 'nrql': { 'query': query or target_condition_nrql['nrql']['query'], 'since_value': since_value or target_condition_nrql['nrql']['since_value'], } } } if enabled is not None: data['nrql_condition']['enabled'] = str(enabled).lower() if runbook_url is not None: data['nrql_condition']['runbook_url'] = runbook_url elif 'runbook_url' in target_condition_nrql: data['nrql_condition']['runbook_url'] = target_condition_nrql['runbook_url'] if expected_groups is not None: data['nrql_condition']['expected_groups'] = expected_groups elif 'expected_groups' in target_condition_nrql: data['nrql_condition']['expected_groups'] = target_condition_nrql['expected_groups'] if ignore_overlap is not None: data['nrql_condition']['ignore_overlap'] = ignore_overlap elif 'ignore_overlap' in target_condition_nrql: data['nrql_condition']['ignore_overlap'] = target_condition_nrql['ignore_overlap'] if value_function is not None: data['nrql_condition']['value_function'] = value_function elif 'value_function' in target_condition_nrql: data['nrql_condition']['value_function'] = target_condition_nrql['value_function'] if data['nrql_condition']['type'] == 'static': if 'value_function' not in data['nrql_condition']: raise ConfigurationException( 'Alert is set as static but no value_function config specified' ) data['nrql_condition'].pop('expected_groups', None) data['nrql_condition'].pop('ignore_overlap', None) elif data['nrql_condition']['type'] == 'outlier': if 'expected_groups' not in data['nrql_condition']: raise ConfigurationException( 'Alert is set as outlier but expected_groups config is not specified' ) if 'ignore_overlap' not in data['nrql_condition']: raise ConfigurationException( 'Alert is set as outlier but ignore_overlap config is not specified' ) data['nrql_condition'].pop('value_function', None) return self._put( url='{0}alerts_nrql_conditions/{1}.json'.format(self.URL, alert_condition_nrql_id), headers=self.headers, data=data )
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 26; 2, function_name:create; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 4, identifier:self; 5, identifier:policy_id; 6, identifier:name; 7, identifier:threshold_type; 8, identifier:query; 9, identifier:since_value; 10, identifier:terms; 11, default_parameter; 11, 12; 11, 13; 12, identifier:expected_groups; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:value_function; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:runbook_url; 19, None; 20, default_parameter; 20, 21; 20, 22; 21, identifier:ignore_overlap; 22, None; 23, default_parameter; 23, 24; 23, 25; 24, identifier:enabled; 25, True; 26, block; 26, 27; 26, 29; 26, 57; 26, 70; 26, 83; 26, 96; 26, 109; 26, 193; 27, expression_statement; 27, 28; 28, comment; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:data; 32, dictionary; 32, 33; 33, pair; 33, 34; 33, 35; 34, string:'nrql_condition'; 35, dictionary; 35, 36; 35, 39; 35, 42; 35, 45; 35, 48; 36, pair; 36, 37; 36, 38; 37, string:'type'; 38, identifier:threshold_type; 39, pair; 39, 40; 39, 41; 40, string:'name'; 41, identifier:name; 42, pair; 42, 43; 42, 44; 43, string:'enabled'; 44, identifier:enabled; 45, pair; 45, 46; 45, 47; 46, string:'terms'; 47, identifier:terms; 48, pair; 48, 49; 48, 50; 49, string:'nrql'; 50, dictionary; 50, 51; 50, 54; 51, pair; 51, 52; 51, 53; 52, string:'query'; 53, identifier:query; 54, pair; 54, 55; 54, 56; 55, string:'since_value'; 56, identifier:since_value; 57, if_statement; 57, 58; 57, 61; 58, comparison_operator:is; 58, 59; 58, 60; 59, identifier:runbook_url; 60, None; 61, block; 61, 62; 62, expression_statement; 62, 63; 63, assignment; 63, 64; 63, 69; 64, subscript; 64, 65; 64, 68; 65, subscript; 65, 66; 65, 67; 66, identifier:data; 67, string:'nrql_condition'; 68, string:'runbook_url'; 69, identifier:runbook_url; 70, if_statement; 70, 71; 70, 74; 71, comparison_operator:is; 71, 72; 71, 73; 72, identifier:expected_groups; 73, None; 74, block; 74, 75; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 82; 77, subscript; 77, 78; 77, 81; 78, subscript; 78, 79; 78, 80; 79, identifier:data; 80, string:'nrql_condition'; 81, string:'expected_groups'; 82, identifier:expected_groups; 83, if_statement; 83, 84; 83, 87; 84, comparison_operator:is; 84, 85; 84, 86; 85, identifier:ignore_overlap; 86, None; 87, block; 87, 88; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 95; 90, subscript; 90, 91; 90, 94; 91, subscript; 91, 92; 91, 93; 92, identifier:data; 93, string:'nrql_condition'; 94, string:'ignore_overlap'; 95, identifier:ignore_overlap; 96, if_statement; 96, 97; 96, 100; 97, comparison_operator:is; 97, 98; 97, 99; 98, identifier:value_function; 99, None; 100, block; 100, 101; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 108; 103, subscript; 103, 104; 103, 107; 104, subscript; 104, 105; 104, 106; 105, identifier:data; 106, string:'nrql_condition'; 107, string:'value_function'; 108, identifier:value_function; 109, if_statement; 109, 110; 109, 117; 109, 150; 110, comparison_operator:==; 110, 111; 110, 116; 111, subscript; 111, 112; 111, 115; 112, subscript; 112, 113; 112, 114; 113, identifier:data; 114, string:'nrql_condition'; 115, string:'type'; 116, string:'static'; 117, block; 117, 118; 117, 130; 117, 140; 118, if_statement; 118, 119; 118, 124; 119, comparison_operator:not; 119, 120; 119, 121; 120, string:'value_function'; 121, subscript; 121, 122; 121, 123; 122, identifier:data; 123, string:'nrql_condition'; 124, block; 124, 125; 125, raise_statement; 125, 126; 126, call; 126, 127; 126, 128; 127, identifier:ConfigurationException; 128, argument_list; 128, 129; 129, string:'Alert is set as static but no value_function config specified'; 130, expression_statement; 130, 131; 131, call; 131, 132; 131, 137; 132, attribute; 132, 133; 132, 136; 133, subscript; 133, 134; 133, 135; 134, identifier:data; 135, string:'nrql_condition'; 136, identifier:pop; 137, argument_list; 137, 138; 137, 139; 138, string:'expected_groups'; 139, None; 140, expression_statement; 140, 141; 141, call; 141, 142; 141, 147; 142, attribute; 142, 143; 142, 146; 143, subscript; 143, 144; 143, 145; 144, identifier:data; 145, string:'nrql_condition'; 146, identifier:pop; 147, argument_list; 147, 148; 147, 149; 148, string:'ignore_overlap'; 149, None; 150, elif_clause; 150, 151; 150, 158; 151, comparison_operator:==; 151, 152; 151, 157; 152, subscript; 152, 153; 152, 156; 153, subscript; 153, 154; 153, 155; 154, identifier:data; 155, string:'nrql_condition'; 156, string:'type'; 157, string:'outlier'; 158, block; 158, 159; 158, 171; 158, 183; 159, if_statement; 159, 160; 159, 165; 160, comparison_operator:not; 160, 161; 160, 162; 161, string:'expected_groups'; 162, subscript; 162, 163; 162, 164; 163, identifier:data; 164, string:'nrql_condition'; 165, block; 165, 166; 166, raise_statement; 166, 167; 167, call; 167, 168; 167, 169; 168, identifier:ConfigurationException; 169, argument_list; 169, 170; 170, string:'Alert is set as outlier but expected_groups config is not specified'; 171, if_statement; 171, 172; 171, 177; 172, comparison_operator:not; 172, 173; 172, 174; 173, string:'ignore_overlap'; 174, subscript; 174, 175; 174, 176; 175, identifier:data; 176, string:'nrql_condition'; 177, block; 177, 178; 178, raise_statement; 178, 179; 179, call; 179, 180; 179, 181; 180, identifier:ConfigurationException; 181, argument_list; 181, 182; 182, string:'Alert is set as outlier but ignore_overlap config is not specified'; 183, expression_statement; 183, 184; 184, call; 184, 185; 184, 190; 185, attribute; 185, 186; 185, 189; 186, subscript; 186, 187; 186, 188; 187, identifier:data; 188, string:'nrql_condition'; 189, identifier:pop; 190, argument_list; 190, 191; 190, 192; 191, string:'value_function'; 192, None; 193, return_statement; 193, 194; 194, call; 194, 195; 194, 198; 195, attribute; 195, 196; 195, 197; 196, identifier:self; 197, identifier:_post; 198, argument_list; 198, 199; 198, 210; 198, 215; 199, keyword_argument; 199, 200; 199, 201; 200, identifier:url; 201, call; 201, 202; 201, 205; 202, attribute; 202, 203; 202, 204; 203, string:'{0}alerts_nrql_conditions/policies/{1}.json'; 204, identifier:format; 205, argument_list; 205, 206; 205, 209; 206, attribute; 206, 207; 206, 208; 207, identifier:self; 208, identifier:URL; 209, identifier:policy_id; 210, keyword_argument; 210, 211; 210, 212; 211, identifier:headers; 212, attribute; 212, 213; 212, 214; 213, identifier:self; 214, identifier:headers; 215, keyword_argument; 215, 216; 215, 217; 216, identifier:data; 217, identifier:data
def create( self, policy_id, name, threshold_type, query, since_value, terms, expected_groups=None, value_function=None, runbook_url=None, ignore_overlap=None, enabled=True): """ Creates an alert condition nrql :type policy_id: int :param policy_id: Alert policy id where target alert condition nrql belongs to :type name: str :param name: The name of the alert :type threshold_type: str :param type: The threshold_type of the condition, can be static or outlier :type query: str :param query: nrql query for the alerts :type since_value: str :param since_value: since value for the alert :type terms: list[hash] :param terms: list of hashes containing threshold config for the alert :type expected_groups: int :param expected_groups: expected groups setting for outlier alerts :type value_function: str :param type: value function for static alerts :type runbook_url: str :param runbook_url: The url of the runbook :type ignore_overlap: bool :param ignore_overlap: Whether to ignore overlaps for outlier alerts :type enabled: bool :param enabled: Whether to enable that alert condition :rtype: dict :return: The JSON response of the API :raises: This will raise a :class:`NewRelicAPIServerException<newrelic_api.exceptions.NoEntityException>` if target alert condition is not included in target policy :raises: This will raise a :class:`ConfigurationException<newrelic_api.exceptions.ConfigurationException>` if metric is set as user_defined but user_defined config is not passed :: { "nrql_condition": { "name": "string", "runbook_url": "string", "enabled": "boolean", "expected_groups": "integer", "ignore_overlap": "boolean", "value_function": "string", "terms": [ { "duration": "string", "operator": "string", "priority": "string", "threshold": "string", "time_function": "string" } ], "nrql": { "query": "string", "since_value": "string" } } } """ data = { 'nrql_condition': { 'type': threshold_type, 'name': name, 'enabled': enabled, 'terms': terms, 'nrql': { 'query': query, 'since_value': since_value } } } if runbook_url is not None: data['nrql_condition']['runbook_url'] = runbook_url if expected_groups is not None: data['nrql_condition']['expected_groups'] = expected_groups if ignore_overlap is not None: data['nrql_condition']['ignore_overlap'] = ignore_overlap if value_function is not None: data['nrql_condition']['value_function'] = value_function if data['nrql_condition']['type'] == 'static': if 'value_function' not in data['nrql_condition']: raise ConfigurationException( 'Alert is set as static but no value_function config specified' ) data['nrql_condition'].pop('expected_groups', None) data['nrql_condition'].pop('ignore_overlap', None) elif data['nrql_condition']['type'] == 'outlier': if 'expected_groups' not in data['nrql_condition']: raise ConfigurationException( 'Alert is set as outlier but expected_groups config is not specified' ) if 'ignore_overlap' not in data['nrql_condition']: raise ConfigurationException( 'Alert is set as outlier but ignore_overlap config is not specified' ) data['nrql_condition'].pop('value_function', None) return self._post( url='{0}alerts_nrql_conditions/policies/{1}.json'.format(self.URL, policy_id), headers=self.headers, data=data )
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 34; 2, function_name:update; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 10; 3, 13; 3, 16; 3, 19; 3, 22; 3, 25; 3, 28; 3, 31; 4, identifier:self; 5, identifier:alert_condition_id; 6, identifier:policy_id; 7, default_parameter; 7, 8; 7, 9; 8, identifier:type; 9, None; 10, default_parameter; 10, 11; 10, 12; 11, identifier:condition_scope; 12, None; 13, default_parameter; 13, 14; 13, 15; 14, identifier:name; 15, None; 16, default_parameter; 16, 17; 16, 18; 17, identifier:entities; 18, None; 19, default_parameter; 19, 20; 19, 21; 20, identifier:metric; 21, None; 22, default_parameter; 22, 23; 22, 24; 23, identifier:runbook_url; 24, None; 25, default_parameter; 25, 26; 25, 27; 26, identifier:terms; 27, None; 28, default_parameter; 28, 29; 28, 30; 29, identifier:user_defined; 30, None; 31, default_parameter; 31, 32; 31, 33; 32, identifier:enabled; 33, None; 34, block; 34, 35; 34, 37; 34, 46; 34, 50; 34, 71; 34, 89; 34, 145; 34, 165; 34, 207; 35, expression_statement; 35, 36; 36, comment; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:conditions_dict; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:self; 43, identifier:list; 44, argument_list; 44, 45; 45, identifier:policy_id; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:target_condition; 49, None; 50, for_statement; 50, 51; 50, 52; 50, 55; 51, identifier:condition; 52, subscript; 52, 53; 52, 54; 53, identifier:conditions_dict; 54, string:'conditions'; 55, block; 55, 56; 56, if_statement; 56, 57; 56, 65; 57, comparison_operator:==; 57, 58; 57, 64; 58, call; 58, 59; 58, 60; 59, identifier:int; 60, argument_list; 60, 61; 61, subscript; 61, 62; 61, 63; 62, identifier:condition; 63, string:'id'; 64, identifier:alert_condition_id; 65, block; 65, 66; 65, 70; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:target_condition; 69, identifier:condition; 70, break_statement; 71, if_statement; 71, 72; 71, 75; 72, comparison_operator:is; 72, 73; 72, 74; 73, identifier:target_condition; 74, None; 75, block; 75, 76; 76, raise_statement; 76, 77; 77, call; 77, 78; 77, 79; 78, identifier:NoEntityException; 79, argument_list; 79, 80; 80, call; 80, 81; 80, 86; 81, attribute; 81, 82; 81, 85; 82, concatenated_string; 82, 83; 82, 84; 83, string:'Target alert condition is not included in that policy.'; 84, string:'policy_id: {}, alert_condition_id {}'; 85, identifier:format; 86, argument_list; 86, 87; 86, 88; 87, identifier:policy_id; 88, identifier:alert_condition_id; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:data; 92, dictionary; 92, 93; 93, pair; 93, 94; 93, 95; 94, string:'condition'; 95, dictionary; 95, 96; 95, 103; 95, 110; 95, 117; 95, 124; 95, 131; 95, 138; 96, pair; 96, 97; 96, 98; 97, string:'type'; 98, boolean_operator:or; 98, 99; 98, 100; 99, identifier:type; 100, subscript; 100, 101; 100, 102; 101, identifier:target_condition; 102, string:'type'; 103, pair; 103, 104; 103, 105; 104, string:'name'; 105, boolean_operator:or; 105, 106; 105, 107; 106, identifier:name; 107, subscript; 107, 108; 107, 109; 108, identifier:target_condition; 109, string:'name'; 110, pair; 110, 111; 110, 112; 111, string:'entities'; 112, boolean_operator:or; 112, 113; 112, 114; 113, identifier:entities; 114, subscript; 114, 115; 114, 116; 115, identifier:target_condition; 116, string:'entities'; 117, pair; 117, 118; 117, 119; 118, string:'condition_scope'; 119, boolean_operator:or; 119, 120; 119, 121; 120, identifier:condition_scope; 121, subscript; 121, 122; 121, 123; 122, identifier:target_condition; 123, string:'condition_scope'; 124, pair; 124, 125; 124, 126; 125, string:'terms'; 126, boolean_operator:or; 126, 127; 126, 128; 127, identifier:terms; 128, subscript; 128, 129; 128, 130; 129, identifier:target_condition; 130, string:'terms'; 131, pair; 131, 132; 131, 133; 132, string:'metric'; 133, boolean_operator:or; 133, 134; 133, 135; 134, identifier:metric; 135, subscript; 135, 136; 135, 137; 136, identifier:target_condition; 137, string:'metric'; 138, pair; 138, 139; 138, 140; 139, string:'runbook_url'; 140, boolean_operator:or; 140, 141; 140, 142; 141, identifier:runbook_url; 142, subscript; 142, 143; 142, 144; 143, identifier:target_condition; 144, string:'runbook_url'; 145, if_statement; 145, 146; 145, 149; 146, comparison_operator:is; 146, 147; 146, 148; 147, identifier:enabled; 148, None; 149, block; 149, 150; 150, expression_statement; 150, 151; 151, assignment; 151, 152; 151, 157; 152, subscript; 152, 153; 152, 156; 153, subscript; 153, 154; 153, 155; 154, identifier:data; 155, string:'condition'; 156, string:'enabled'; 157, call; 157, 158; 157, 164; 158, attribute; 158, 159; 158, 163; 159, call; 159, 160; 159, 161; 160, identifier:str; 161, argument_list; 161, 162; 162, identifier:enabled; 163, identifier:lower; 164, argument_list; 165, if_statement; 165, 166; 165, 173; 166, comparison_operator:==; 166, 167; 166, 172; 167, subscript; 167, 168; 167, 171; 168, subscript; 168, 169; 168, 170; 169, identifier:data; 170, string:'condition'; 171, string:'metric'; 172, string:'user_defined'; 173, block; 173, 174; 174, if_statement; 174, 175; 174, 176; 174, 185; 174, 200; 175, identifier:user_defined; 176, block; 176, 177; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 184; 179, subscript; 179, 180; 179, 183; 180, subscript; 180, 181; 180, 182; 181, identifier:data; 182, string:'condition'; 183, string:'user_defined'; 184, identifier:user_defined; 185, elif_clause; 185, 186; 185, 189; 186, comparison_operator:in; 186, 187; 186, 188; 187, string:'user_defined'; 188, identifier:target_condition; 189, block; 189, 190; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 197; 192, subscript; 192, 193; 192, 196; 193, subscript; 193, 194; 193, 195; 194, identifier:data; 195, string:'condition'; 196, string:'user_defined'; 197, subscript; 197, 198; 197, 199; 198, identifier:target_condition; 199, string:'user_defined'; 200, else_clause; 200, 201; 201, block; 201, 202; 202, raise_statement; 202, 203; 203, call; 203, 204; 203, 205; 204, identifier:ConfigurationException; 205, argument_list; 205, 206; 206, string:'Metric is set as user_defined but no user_defined config specified'; 207, return_statement; 207, 208; 208, call; 208, 209; 208, 212; 209, attribute; 209, 210; 209, 211; 210, identifier:self; 211, identifier:_put; 212, argument_list; 212, 213; 212, 224; 212, 229; 213, keyword_argument; 213, 214; 213, 215; 214, identifier:url; 215, call; 215, 216; 215, 219; 216, attribute; 216, 217; 216, 218; 217, string:'{0}alerts_conditions/{1}.json'; 218, identifier:format; 219, argument_list; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:self; 222, identifier:URL; 223, identifier:alert_condition_id; 224, keyword_argument; 224, 225; 224, 226; 225, identifier:headers; 226, attribute; 226, 227; 226, 228; 227, identifier:self; 228, identifier:headers; 229, keyword_argument; 229, 230; 229, 231; 230, identifier:data; 231, identifier:data
def update( self, alert_condition_id, policy_id, type=None, condition_scope=None, name=None, entities=None, metric=None, runbook_url=None, terms=None, user_defined=None, enabled=None): """ Updates any of the optional parameters of the alert condition :type alert_condition_id: int :param alert_condition_id: Alerts condition id to update :type policy_id: int :param policy_id: Alert policy id where target alert condition belongs to :type type: str :param type: The type of the condition, can be apm_app_metric, apm_kt_metric, servers_metric, browser_metric, mobile_metric :type condition_scope: str :param condition_scope: The scope of the condition, can be instance or application :type name: str :param name: The name of the server :type entities: list[str] :param name: entity ids to which the alert condition is applied :type : str :param metric: The target metric :type : str :param runbook_url: The url of the runbook :type terms: list[hash] :param terms: list of hashes containing threshold config for the alert :type user_defined: hash :param user_defined: hash containing threshold user_defined for the alert required if metric is set to user_defined :type enabled: bool :param enabled: Whether to enable that alert condition :rtype: dict :return: The JSON response of the API :raises: This will raise a :class:`NewRelicAPIServerException<newrelic_api.exceptions.NoEntityException>` if target alert condition is not included in target policy :raises: This will raise a :class:`ConfigurationException<newrelic_api.exceptions.ConfigurationException>` if metric is set as user_defined but user_defined config is not passed :: { "condition": { "id": "integer", "type": "string", "condition_scope": "string", "name": "string", "enabled": "boolean", "entities": [ "integer" ], "metric": "string", "runbook_url": "string", "terms": [ { "duration": "string", "operator": "string", "priority": "string", "threshold": "string", "time_function": "string" } ], "user_defined": { "metric": "string", "value_function": "string" } } } """ conditions_dict = self.list(policy_id) target_condition = None for condition in conditions_dict['conditions']: if int(condition['id']) == alert_condition_id: target_condition = condition break if target_condition is None: raise NoEntityException( 'Target alert condition is not included in that policy.' 'policy_id: {}, alert_condition_id {}'.format(policy_id, alert_condition_id) ) data = { 'condition': { 'type': type or target_condition['type'], 'name': name or target_condition['name'], 'entities': entities or target_condition['entities'], 'condition_scope': condition_scope or target_condition['condition_scope'], 'terms': terms or target_condition['terms'], 'metric': metric or target_condition['metric'], 'runbook_url': runbook_url or target_condition['runbook_url'], } } if enabled is not None: data['condition']['enabled'] = str(enabled).lower() if data['condition']['metric'] == 'user_defined': if user_defined: data['condition']['user_defined'] = user_defined elif 'user_defined' in target_condition: data['condition']['user_defined'] = target_condition['user_defined'] else: raise ConfigurationException( 'Metric is set as user_defined but no user_defined config specified' ) return self._put( url='{0}alerts_conditions/{1}.json'.format(self.URL, alert_condition_id), headers=self.headers, data=data )
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:operatorPrecedence; 3, parameters; 3, 4; 3, 5; 4, identifier:base; 5, identifier:operators; 6, block; 6, 7; 6, 9; 6, 10; 6, 16; 6, 17; 6, 33; 6, 53; 6, 226; 6, 227; 6, 231; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:expression; 13, call; 13, 14; 13, 15; 14, identifier:Forward; 15, argument_list; 16, comment; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:last; 20, binary_operator:|; 20, 21; 20, 22; 21, identifier:base; 22, binary_operator:+; 22, 23; 22, 29; 23, binary_operator:+; 23, 24; 23, 28; 24, call; 24, 25; 24, 26; 25, identifier:Suppress; 26, argument_list; 26, 27; 27, string:'('; 28, identifier:expression; 29, call; 29, 30; 29, 31; 30, identifier:Suppress; 31, argument_list; 31, 32; 32, string:')'; 33, function_definition; 33, 34; 33, 35; 33, 45; 34, function_name:parse_operator; 35, parameters; 35, 36; 35, 37; 35, 38; 35, 39; 35, 42; 36, identifier:expr; 37, identifier:arity; 38, identifier:association; 39, default_parameter; 39, 40; 39, 41; 40, identifier:action; 41, None; 42, default_parameter; 42, 43; 42, 44; 43, identifier:extra; 44, None; 45, block; 45, 46; 46, return_statement; 46, 47; 47, expression_list; 47, 48; 47, 49; 47, 50; 47, 51; 47, 52; 48, identifier:expr; 49, identifier:arity; 50, identifier:association; 51, identifier:action; 52, identifier:extra; 53, for_statement; 53, 54; 53, 55; 53, 56; 53, 57; 54, identifier:op; 55, identifier:operators; 56, comment; 57, block; 57, 58; 57, 71; 57, 72; 57, 86; 57, 102; 57, 103; 57, 109; 57, 110; 57, 202; 57, 203; 57, 215; 57, 222; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 66; 60, pattern_list; 60, 61; 60, 62; 60, 63; 60, 64; 60, 65; 61, identifier:expr; 62, identifier:arity; 63, identifier:association; 64, identifier:action; 65, identifier:extra; 66, call; 66, 67; 66, 68; 67, identifier:parse_operator; 68, argument_list; 68, 69; 69, list_splat; 69, 70; 70, identifier:op; 71, comment; 72, if_statement; 72, 73; 72, 80; 73, boolean_operator:or; 73, 74; 73, 77; 74, comparison_operator:<; 74, 75; 74, 76; 75, identifier:arity; 76, integer:1; 77, comparison_operator:>; 77, 78; 77, 79; 78, identifier:arity; 79, integer:2; 80, block; 80, 81; 81, raise_statement; 81, 82; 82, call; 82, 83; 82, 84; 83, identifier:Exception; 84, argument_list; 84, 85; 85, string:"Arity must be unary (1) or binary (2)"; 86, if_statement; 86, 87; 86, 96; 87, comparison_operator:not; 87, 88; 87, 89; 88, identifier:association; 89, tuple; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:opAssoc; 92, identifier:LEFT; 93, attribute; 93, 94; 93, 95; 94, identifier:opAssoc; 95, identifier:RIGHT; 96, block; 96, 97; 97, raise_statement; 97, 98; 98, call; 98, 99; 98, 100; 99, identifier:Exception; 100, argument_list; 100, 101; 101, string:"Association must be LEFT or RIGHT"; 102, comment; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:this; 106, call; 106, 107; 106, 108; 107, identifier:Forward; 108, argument_list; 109, comment; 110, if_statement; 110, 111; 110, 116; 110, 157; 111, comparison_operator:is; 111, 112; 111, 113; 112, identifier:association; 113, attribute; 113, 114; 113, 115; 114, identifier:opAssoc; 115, identifier:LEFT; 116, block; 116, 117; 116, 127; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:new_last; 120, conditional_expression:if; 120, 121; 120, 125; 120, 126; 121, parenthesized_expression; 121, 122; 122, binary_operator:|; 122, 123; 122, 124; 123, identifier:last; 124, identifier:extra; 125, identifier:extra; 126, identifier:last; 127, if_statement; 127, 128; 127, 131; 127, 141; 128, comparison_operator:==; 128, 129; 128, 130; 129, identifier:arity; 130, integer:1; 131, block; 131, 132; 132, expression_statement; 132, 133; 133, assignment; 133, 134; 133, 135; 134, identifier:operator_expression; 135, binary_operator:+; 135, 136; 135, 137; 136, identifier:new_last; 137, call; 137, 138; 137, 139; 138, identifier:OneOrMore; 139, argument_list; 139, 140; 140, identifier:expr; 141, elif_clause; 141, 142; 141, 145; 142, comparison_operator:==; 142, 143; 142, 144; 143, identifier:arity; 144, integer:2; 145, block; 145, 146; 146, expression_statement; 146, 147; 147, assignment; 147, 148; 147, 149; 148, identifier:operator_expression; 149, binary_operator:+; 149, 150; 149, 151; 150, identifier:last; 151, call; 151, 152; 151, 153; 152, identifier:OneOrMore; 153, argument_list; 153, 154; 154, binary_operator:+; 154, 155; 154, 156; 155, identifier:expr; 156, identifier:new_last; 157, elif_clause; 157, 158; 157, 163; 158, comparison_operator:is; 158, 159; 158, 160; 159, identifier:association; 160, attribute; 160, 161; 160, 162; 161, identifier:opAssoc; 162, identifier:RIGHT; 163, block; 163, 164; 163, 174; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 167; 166, identifier:new_this; 167, conditional_expression:if; 167, 168; 167, 172; 167, 173; 168, parenthesized_expression; 168, 169; 169, binary_operator:|; 169, 170; 169, 171; 170, identifier:this; 171, identifier:extra; 172, identifier:extra; 173, identifier:this; 174, if_statement; 174, 175; 174, 178; 174, 185; 174, 186; 175, comparison_operator:==; 175, 176; 175, 177; 176, identifier:arity; 177, integer:1; 178, block; 178, 179; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:operator_expression; 182, binary_operator:+; 182, 183; 182, 184; 183, identifier:expr; 184, identifier:new_this; 185, comment; 186, elif_clause; 186, 187; 186, 190; 186, 191; 187, comparison_operator:==; 187, 188; 187, 189; 188, identifier:arity; 189, integer:2; 190, comment; 191, block; 191, 192; 191, 201; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 195; 194, identifier:operator_expression; 195, binary_operator:+; 195, 196; 195, 197; 196, identifier:last; 197, call; 197, 198; 197, 199; 198, identifier:OneOrMore; 199, argument_list; 199, 200; 200, identifier:new_this; 201, comment; 202, comment; 203, if_statement; 203, 204; 203, 207; 204, comparison_operator:is; 204, 205; 204, 206; 205, identifier:action; 206, None; 207, block; 207, 208; 208, expression_statement; 208, 209; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:operator_expression; 212, identifier:setParseAction; 213, argument_list; 213, 214; 214, identifier:action; 215, expression_statement; 215, 216; 216, augmented_assignment:<<=; 216, 217; 216, 218; 217, identifier:this; 218, parenthesized_expression; 218, 219; 219, binary_operator:|; 219, 220; 219, 221; 220, identifier:operator_expression; 221, identifier:last; 222, expression_statement; 222, 223; 223, assignment; 223, 224; 223, 225; 224, identifier:last; 225, identifier:this; 226, comment; 227, expression_statement; 227, 228; 228, augmented_assignment:<<=; 228, 229; 228, 230; 229, identifier:expression; 230, identifier:last; 231, return_statement; 231, 232; 232, identifier:expression
def operatorPrecedence(base, operators): """ This re-implements pyparsing's operatorPrecedence function. It gets rid of a few annoying bugs, like always putting operators inside a Group, and matching the whole grammar with Forward first (there may actually be a reason for that, but I couldn't find it). It doesn't support trinary expressions, but they should be easy to add if it turns out I need them. """ # The full expression, used to provide sub-expressions expression = Forward() # The initial expression last = base | Suppress('(') + expression + Suppress(')') def parse_operator(expr, arity, association, action=None, extra=None): return expr, arity, association, action, extra for op in operators: # Use a function to default action to None expr, arity, association, action, extra = parse_operator(*op) # Check that the arity is valid if arity < 1 or arity > 2: raise Exception("Arity must be unary (1) or binary (2)") if association not in (opAssoc.LEFT, opAssoc.RIGHT): raise Exception("Association must be LEFT or RIGHT") # This will contain the expression this = Forward() # Create an expression based on the association and arity if association is opAssoc.LEFT: new_last = (last | extra) if extra else last if arity == 1: operator_expression = new_last + OneOrMore(expr) elif arity == 2: operator_expression = last + OneOrMore(expr + new_last) elif association is opAssoc.RIGHT: new_this = (this | extra) if extra else this if arity == 1: operator_expression = expr + new_this # Currently no operator uses this, so marking it nocover for now elif arity == 2: # nocover operator_expression = last + OneOrMore(new_this) # nocover # Set the parse action for the operator if action is not None: operator_expression.setParseAction(action) this <<= (operator_expression | last) last = this # Set the full expression and return it expression <<= last return expression
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:readGraph; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 4, identifier:edgeList; 5, default_parameter; 5, 6; 5, 7; 6, identifier:nodeList; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:directed; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:idKey; 13, string:'ID'; 14, default_parameter; 14, 15; 14, 16; 15, identifier:eSource; 16, string:'From'; 17, default_parameter; 17, 18; 17, 19; 18, identifier:eDest; 19, string:'To'; 20, block; 20, 21; 20, 23; 20, 29; 20, 50; 21, expression_statement; 21, 22; 22, comment; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:progArgs; 26, tuple; 26, 27; 26, 28; 27, integer:0; 28, string:"Starting to reading graphs"; 29, if_statement; 29, 30; 29, 33; 29, 41; 30, attribute; 30, 31; 30, 32; 31, identifier:metaknowledge; 32, identifier:VERBOSE_MODE; 33, block; 33, 34; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:progKwargs; 37, dictionary; 37, 38; 38, pair; 38, 39; 38, 40; 39, string:'dummy'; 40, False; 41, else_clause; 41, 42; 42, block; 42, 43; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:progKwargs; 46, dictionary; 46, 47; 47, pair; 47, 48; 47, 49; 48, string:'dummy'; 49, True; 50, with_statement; 50, 51; 50, 63; 51, with_clause; 51, 52; 52, with_item; 52, 53; 53, as_pattern; 53, 54; 53, 61; 54, call; 54, 55; 54, 56; 55, identifier:_ProgressBar; 56, argument_list; 56, 57; 56, 59; 57, list_splat; 57, 58; 58, identifier:progArgs; 59, dictionary_splat; 59, 60; 60, identifier:progKwargs; 61, as_pattern_target; 61, 62; 62, identifier:PBar; 63, block; 63, 64; 63, 85; 63, 178; 63, 188; 63, 209; 63, 218; 63, 274; 63, 301; 63, 307; 64, if_statement; 64, 65; 64, 66; 64, 75; 65, identifier:directed; 66, block; 66, 67; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:grph; 70, call; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:nx; 73, identifier:DiGraph; 74, argument_list; 75, else_clause; 75, 76; 76, block; 76, 77; 77, expression_statement; 77, 78; 78, assignment; 78, 79; 78, 80; 79, identifier:grph; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:nx; 83, identifier:Graph; 84, argument_list; 85, if_statement; 85, 86; 85, 87; 86, identifier:nodeList; 87, block; 87, 88; 87, 98; 87, 119; 87, 128; 87, 172; 88, expression_statement; 88, 89; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:PBar; 92, identifier:updateVal; 93, argument_list; 93, 94; 93, 95; 94, integer:0; 95, binary_operator:+; 95, 96; 95, 97; 96, string:"Reading "; 97, identifier:nodeList; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:f; 101, call; 101, 102; 101, 103; 102, identifier:open; 103, argument_list; 103, 104; 104, call; 104, 105; 104, 110; 105, attribute; 105, 106; 105, 109; 106, attribute; 106, 107; 106, 108; 107, identifier:os; 108, identifier:path; 109, identifier:expanduser; 110, argument_list; 110, 111; 111, call; 111, 112; 111, 117; 112, attribute; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:os; 115, identifier:path; 116, identifier:abspath; 117, argument_list; 117, 118; 118, identifier:nodeList; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:nFile; 122, call; 122, 123; 122, 126; 123, attribute; 123, 124; 123, 125; 124, identifier:csv; 125, identifier:DictReader; 126, argument_list; 126, 127; 127, identifier:f; 128, for_statement; 128, 129; 128, 130; 128, 131; 129, identifier:line; 130, identifier:nFile; 131, block; 131, 132; 131, 136; 131, 142; 131, 146; 132, expression_statement; 132, 133; 133, assignment; 133, 134; 133, 135; 134, identifier:vals; 135, identifier:line; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:ndID; 139, subscript; 139, 140; 139, 141; 140, identifier:vals; 141, identifier:idKey; 142, delete_statement; 142, 143; 143, subscript; 143, 144; 143, 145; 144, identifier:vals; 145, identifier:idKey; 146, if_statement; 146, 147; 146, 153; 146, 163; 147, comparison_operator:>; 147, 148; 147, 152; 148, call; 148, 149; 148, 150; 149, identifier:len; 150, argument_list; 150, 151; 151, identifier:vals; 152, integer:0; 153, block; 153, 154; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:grph; 158, identifier:add_node; 159, argument_list; 159, 160; 159, 161; 160, identifier:ndID; 161, dictionary_splat; 161, 162; 162, identifier:vals; 163, else_clause; 163, 164; 164, block; 164, 165; 165, expression_statement; 165, 166; 166, call; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:grph; 169, identifier:add_node; 170, argument_list; 170, 171; 171, identifier:ndID; 172, expression_statement; 172, 173; 173, call; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:f; 176, identifier:close; 177, argument_list; 178, expression_statement; 178, 179; 179, call; 179, 180; 179, 183; 180, attribute; 180, 181; 180, 182; 181, identifier:PBar; 182, identifier:updateVal; 183, argument_list; 183, 184; 183, 185; 184, float:.25; 185, binary_operator:+; 185, 186; 185, 187; 186, string:"Reading "; 187, identifier:edgeList; 188, expression_statement; 188, 189; 189, assignment; 189, 190; 189, 191; 190, identifier:f; 191, call; 191, 192; 191, 193; 192, identifier:open; 193, argument_list; 193, 194; 194, call; 194, 195; 194, 200; 195, attribute; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:os; 198, identifier:path; 199, identifier:expanduser; 200, argument_list; 200, 201; 201, call; 201, 202; 201, 207; 202, attribute; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:os; 205, identifier:path; 206, identifier:abspath; 207, argument_list; 207, 208; 208, identifier:edgeList; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:eFile; 212, call; 212, 213; 212, 216; 213, attribute; 213, 214; 213, 215; 214, identifier:csv; 215, identifier:DictReader; 216, argument_list; 216, 217; 217, identifier:f; 218, for_statement; 218, 219; 218, 220; 218, 221; 219, identifier:line; 220, identifier:eFile; 221, block; 221, 222; 221, 226; 221, 232; 221, 238; 221, 242; 221, 246; 222, expression_statement; 222, 223; 223, assignment; 223, 224; 223, 225; 224, identifier:vals; 225, identifier:line; 226, expression_statement; 226, 227; 227, assignment; 227, 228; 227, 229; 228, identifier:eFrom; 229, subscript; 229, 230; 229, 231; 230, identifier:vals; 231, identifier:eSource; 232, expression_statement; 232, 233; 233, assignment; 233, 234; 233, 235; 234, identifier:eTo; 235, subscript; 235, 236; 235, 237; 236, identifier:vals; 237, identifier:eDest; 238, delete_statement; 238, 239; 239, subscript; 239, 240; 239, 241; 240, identifier:vals; 241, identifier:eSource; 242, delete_statement; 242, 243; 243, subscript; 243, 244; 243, 245; 244, identifier:vals; 245, identifier:eDest; 246, if_statement; 246, 247; 246, 253; 246, 264; 247, comparison_operator:>; 247, 248; 247, 252; 248, call; 248, 249; 248, 250; 249, identifier:len; 250, argument_list; 250, 251; 251, identifier:vals; 252, integer:0; 253, block; 253, 254; 254, expression_statement; 254, 255; 255, call; 255, 256; 255, 259; 256, attribute; 256, 257; 256, 258; 257, identifier:grph; 258, identifier:add_edge; 259, argument_list; 259, 260; 259, 261; 259, 262; 260, identifier:eFrom; 261, identifier:eTo; 262, dictionary_splat; 262, 263; 263, identifier:vals; 264, else_clause; 264, 265; 265, block; 265, 266; 266, expression_statement; 266, 267; 267, call; 267, 268; 267, 271; 268, attribute; 268, 269; 268, 270; 269, identifier:grph; 270, identifier:add_edge; 271, argument_list; 271, 272; 271, 273; 272, identifier:eFrom; 273, identifier:eTo; 274, expression_statement; 274, 275; 275, call; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:PBar; 278, identifier:finish; 279, argument_list; 279, 280; 280, call; 280, 281; 280, 284; 281, attribute; 281, 282; 281, 283; 282, string:"{} nodes and {} edges found"; 283, identifier:format; 284, argument_list; 284, 285; 284, 293; 285, call; 285, 286; 285, 287; 286, identifier:len; 287, argument_list; 287, 288; 288, call; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:grph; 291, identifier:nodes; 292, argument_list; 293, call; 293, 294; 293, 295; 294, identifier:len; 295, argument_list; 295, 296; 296, call; 296, 297; 296, 300; 297, attribute; 297, 298; 297, 299; 298, identifier:grph; 299, identifier:edges; 300, argument_list; 301, expression_statement; 301, 302; 302, call; 302, 303; 302, 306; 303, attribute; 303, 304; 303, 305; 304, identifier:f; 305, identifier:close; 306, argument_list; 307, return_statement; 307, 308; 308, identifier:grph
def readGraph(edgeList, nodeList = None, directed = False, idKey = 'ID', eSource = 'From', eDest = 'To'): """Reads the files given by _edgeList_ and _nodeList_ and creates a networkx graph for the files. This is designed only for the files produced by metaknowledge and is meant to be the reverse of [writeGraph()](#metaknowledge.graphHelpers.writeGraph), if this does not produce the desired results the networkx builtin [networkx.read_edgelist()](https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.readwrite.edgelist.read_edgelist.html) could be tried as it is aimed at a more general usage. The read edge list format assumes the column named _eSource_ (default `'From'`) is the source node, then the column _eDest_ (default `'To'`) givens the destination and all other columns are attributes of the edges, e.g. weight. The read node list format assumes the column _idKey_ (default `'ID'`) is the ID of the node for the edge list and the resulting network. All other columns are considered attributes of the node, e.g. count. **Note**: If the names of the columns do not match those given to **readGraph()** a `KeyError` exception will be raised. **Note**: If nodes appear in the edgelist but not the nodeList they will be created silently with no attributes. # Parameters _edgeList_ : `str` > a string giving the path to the edge list file _nodeList_ : `optional [str]` > default `None`, a string giving the path to the node list file _directed_ : `optional [bool]` > default `False`, if `True` the produced network is directed from _eSource_ to _eDest_ _idKey_ : `optional [str]` > default `'ID'`, the name of the ID column in the node list _eSource_ : `optional [str]` > default `'From'`, the name of the source column in the edge list _eDest_ : `optional [str]` > default `'To'`, the name of the destination column in the edge list # Returns `networkx Graph` > the graph described by the input files """ progArgs = (0, "Starting to reading graphs") if metaknowledge.VERBOSE_MODE: progKwargs = {'dummy' : False} else: progKwargs = {'dummy' : True} with _ProgressBar(*progArgs, **progKwargs) as PBar: if directed: grph = nx.DiGraph() else: grph = nx.Graph() if nodeList: PBar.updateVal(0, "Reading " + nodeList) f = open(os.path.expanduser(os.path.abspath(nodeList))) nFile = csv.DictReader(f) for line in nFile: vals = line ndID = vals[idKey] del vals[idKey] if len(vals) > 0: grph.add_node(ndID, **vals) else: grph.add_node(ndID) f.close() PBar.updateVal(.25, "Reading " + edgeList) f = open(os.path.expanduser(os.path.abspath(edgeList))) eFile = csv.DictReader(f) for line in eFile: vals = line eFrom = vals[eSource] eTo = vals[eDest] del vals[eSource] del vals[eDest] if len(vals) > 0: grph.add_edge(eFrom, eTo, **vals) else: grph.add_edge(eFrom, eTo) PBar.finish("{} nodes and {} edges found".format(len(grph.nodes()), len(grph.edges()))) f.close() return grph
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 21; 2, function_name:writeGraph; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 4, identifier:grph; 5, identifier:name; 6, default_parameter; 6, 7; 6, 8; 7, identifier:edgeInfo; 8, True; 9, default_parameter; 9, 10; 9, 11; 10, identifier:typing; 11, False; 12, default_parameter; 12, 13; 12, 14; 13, identifier:suffix; 14, string:'csv'; 15, default_parameter; 15, 16; 15, 17; 16, identifier:overwrite; 17, True; 18, default_parameter; 18, 19; 18, 20; 19, identifier:allSameAttribute; 20, False; 21, block; 21, 22; 21, 24; 21, 35; 21, 56; 22, expression_statement; 22, 23; 23, comment; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:progArgs; 27, tuple; 27, 28; 27, 29; 28, integer:0; 29, call; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, string:"Writing the graph to files starting with: {}"; 32, identifier:format; 33, argument_list; 33, 34; 34, identifier:name; 35, if_statement; 35, 36; 35, 39; 35, 47; 36, attribute; 36, 37; 36, 38; 37, identifier:metaknowledge; 38, identifier:VERBOSE_MODE; 39, block; 39, 40; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:progKwargs; 43, dictionary; 43, 44; 44, pair; 44, 45; 44, 46; 45, string:'dummy'; 46, False; 47, else_clause; 47, 48; 48, block; 48, 49; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:progKwargs; 52, dictionary; 52, 53; 53, pair; 53, 54; 53, 55; 54, string:'dummy'; 55, True; 56, with_statement; 56, 57; 56, 69; 57, with_clause; 57, 58; 58, with_item; 58, 59; 59, as_pattern; 59, 60; 59, 67; 60, call; 60, 61; 60, 62; 61, identifier:_ProgressBar; 62, argument_list; 62, 63; 62, 65; 63, list_splat; 63, 64; 64, identifier:progArgs; 65, dictionary_splat; 65, 66; 66, identifier:progKwargs; 67, as_pattern_target; 67, 68; 68, identifier:PBar; 69, block; 69, 70; 69, 114; 69, 139; 69, 304; 69, 342; 69, 357; 69, 369; 70, if_statement; 70, 71; 70, 72; 70, 108; 71, identifier:typing; 72, block; 72, 73; 73, if_statement; 73, 74; 73, 97; 73, 102; 74, boolean_operator:or; 74, 75; 74, 86; 75, call; 75, 76; 75, 77; 76, identifier:isinstance; 77, argument_list; 77, 78; 77, 79; 78, identifier:grph; 79, attribute; 79, 80; 79, 85; 80, attribute; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:nx; 83, identifier:classes; 84, identifier:digraph; 85, identifier:DiGraph; 86, call; 86, 87; 86, 88; 87, identifier:isinstance; 88, argument_list; 88, 89; 88, 90; 89, identifier:grph; 90, attribute; 90, 91; 90, 96; 91, attribute; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:nx; 94, identifier:classes; 95, identifier:multidigraph; 96, identifier:MultiDiGraph; 97, block; 97, 98; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 101; 100, identifier:grphType; 101, string:"_directed"; 102, else_clause; 102, 103; 103, block; 103, 104; 104, expression_statement; 104, 105; 105, assignment; 105, 106; 105, 107; 106, identifier:grphType; 107, string:"_undirected"; 108, else_clause; 108, 109; 109, block; 109, 110; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:grphType; 113, string:''; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:nameCompts; 117, call; 117, 118; 117, 123; 118, attribute; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:os; 121, identifier:path; 122, identifier:split; 123, argument_list; 123, 124; 124, call; 124, 125; 124, 130; 125, attribute; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:os; 128, identifier:path; 129, identifier:expanduser; 130, argument_list; 130, 131; 131, call; 131, 132; 131, 137; 132, attribute; 132, 133; 132, 136; 133, attribute; 133, 134; 133, 135; 134, identifier:os; 135, identifier:path; 136, identifier:normpath; 137, argument_list; 137, 138; 138, identifier:name; 139, if_statement; 139, 140; 139, 151; 139, 172; 139, 207; 139, 254; 140, boolean_operator:and; 140, 141; 140, 146; 141, comparison_operator:==; 141, 142; 141, 145; 142, subscript; 142, 143; 142, 144; 143, identifier:nameCompts; 144, integer:0; 145, string:''; 146, comparison_operator:==; 146, 147; 146, 150; 147, subscript; 147, 148; 147, 149; 148, identifier:nameCompts; 149, integer:1; 150, string:''; 151, block; 151, 152; 151, 162; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:edgeListName; 155, binary_operator:+; 155, 156; 155, 161; 156, binary_operator:+; 156, 157; 156, 160; 157, binary_operator:+; 157, 158; 157, 159; 158, string:"edgeList"; 159, identifier:grphType; 160, string:'.'; 161, identifier:suffix; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:nodesAtrName; 165, binary_operator:+; 165, 166; 165, 171; 166, binary_operator:+; 166, 167; 166, 170; 167, binary_operator:+; 167, 168; 167, 169; 168, string:"nodeAttributes"; 169, identifier:grphType; 170, string:'.'; 171, identifier:suffix; 172, elif_clause; 172, 173; 172, 178; 173, comparison_operator:==; 173, 174; 173, 177; 174, subscript; 174, 175; 174, 176; 175, identifier:nameCompts; 176, integer:0; 177, string:''; 178, block; 178, 179; 178, 193; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:edgeListName; 182, binary_operator:+; 182, 183; 182, 192; 183, binary_operator:+; 183, 184; 183, 191; 184, binary_operator:+; 184, 185; 184, 190; 185, binary_operator:+; 185, 186; 185, 189; 186, subscript; 186, 187; 186, 188; 187, identifier:nameCompts; 188, integer:1; 189, string:"_edgeList"; 190, identifier:grphType; 191, string:'.'; 192, identifier:suffix; 193, expression_statement; 193, 194; 194, assignment; 194, 195; 194, 196; 195, identifier:nodesAtrName; 196, binary_operator:+; 196, 197; 196, 206; 197, binary_operator:+; 197, 198; 197, 205; 198, binary_operator:+; 198, 199; 198, 204; 199, binary_operator:+; 199, 200; 199, 203; 200, subscript; 200, 201; 200, 202; 201, identifier:nameCompts; 202, integer:1; 203, string:"_nodeAttributes"; 204, identifier:grphType; 205, string:'.'; 206, identifier:suffix; 207, elif_clause; 207, 208; 207, 213; 208, comparison_operator:==; 208, 209; 208, 212; 209, subscript; 209, 210; 209, 211; 210, identifier:nameCompts; 211, integer:1; 212, string:''; 213, block; 213, 214; 213, 234; 214, expression_statement; 214, 215; 215, assignment; 215, 216; 215, 217; 216, identifier:edgeListName; 217, call; 217, 218; 217, 223; 218, attribute; 218, 219; 218, 222; 219, attribute; 219, 220; 219, 221; 220, identifier:os; 221, identifier:path; 222, identifier:join; 223, argument_list; 223, 224; 223, 227; 224, subscript; 224, 225; 224, 226; 225, identifier:nameCompts; 226, integer:0; 227, binary_operator:+; 227, 228; 227, 233; 228, binary_operator:+; 228, 229; 228, 232; 229, binary_operator:+; 229, 230; 229, 231; 230, string:"edgeList"; 231, identifier:grphType; 232, string:'.'; 233, identifier:suffix; 234, expression_statement; 234, 235; 235, assignment; 235, 236; 235, 237; 236, identifier:nodesAtrName; 237, call; 237, 238; 237, 243; 238, attribute; 238, 239; 238, 242; 239, attribute; 239, 240; 239, 241; 240, identifier:os; 241, identifier:path; 242, identifier:join; 243, argument_list; 243, 244; 243, 247; 244, subscript; 244, 245; 244, 246; 245, identifier:nameCompts; 246, integer:0; 247, binary_operator:+; 247, 248; 247, 253; 248, binary_operator:+; 248, 249; 248, 252; 249, binary_operator:+; 249, 250; 249, 251; 250, string:"nodeAttributes"; 251, identifier:grphType; 252, string:'.'; 253, identifier:suffix; 254, else_clause; 254, 255; 255, block; 255, 256; 255, 280; 256, expression_statement; 256, 257; 257, assignment; 257, 258; 257, 259; 258, identifier:edgeListName; 259, call; 259, 260; 259, 265; 260, attribute; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, identifier:os; 263, identifier:path; 264, identifier:join; 265, argument_list; 265, 266; 265, 269; 266, subscript; 266, 267; 266, 268; 267, identifier:nameCompts; 268, integer:0; 269, binary_operator:+; 269, 270; 269, 279; 270, binary_operator:+; 270, 271; 270, 278; 271, binary_operator:+; 271, 272; 271, 277; 272, binary_operator:+; 272, 273; 272, 276; 273, subscript; 273, 274; 273, 275; 274, identifier:nameCompts; 275, integer:1; 276, string:"_edgeList"; 277, identifier:grphType; 278, string:'.'; 279, identifier:suffix; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:nodesAtrName; 283, call; 283, 284; 283, 289; 284, attribute; 284, 285; 284, 288; 285, attribute; 285, 286; 285, 287; 286, identifier:os; 287, identifier:path; 288, identifier:join; 289, argument_list; 289, 290; 289, 293; 290, subscript; 290, 291; 290, 292; 291, identifier:nameCompts; 292, integer:0; 293, binary_operator:+; 293, 294; 293, 303; 294, binary_operator:+; 294, 295; 294, 302; 295, binary_operator:+; 295, 296; 295, 301; 296, binary_operator:+; 296, 297; 296, 300; 297, subscript; 297, 298; 297, 299; 298, identifier:nameCompts; 299, integer:1; 300, string:"_nodeAttributes"; 301, identifier:grphType; 302, string:'.'; 303, identifier:suffix; 304, if_statement; 304, 305; 304, 307; 305, not_operator; 305, 306; 306, identifier:overwrite; 307, block; 307, 308; 307, 325; 308, if_statement; 308, 309; 308, 317; 309, call; 309, 310; 309, 315; 310, attribute; 310, 311; 310, 314; 311, attribute; 311, 312; 311, 313; 312, identifier:os; 313, identifier:path; 314, identifier:isfile; 315, argument_list; 315, 316; 316, identifier:edgeListName; 317, block; 317, 318; 318, raise_statement; 318, 319; 319, call; 319, 320; 319, 321; 320, identifier:OSError; 321, argument_list; 321, 322; 322, binary_operator:+; 322, 323; 322, 324; 323, identifier:edgeListName; 324, string:" already exists"; 325, if_statement; 325, 326; 325, 334; 326, call; 326, 327; 326, 332; 327, attribute; 327, 328; 327, 331; 328, attribute; 328, 329; 328, 330; 329, identifier:os; 330, identifier:path; 331, identifier:isfile; 332, argument_list; 332, 333; 333, identifier:nodesAtrName; 334, block; 334, 335; 335, raise_statement; 335, 336; 336, call; 336, 337; 336, 338; 337, identifier:OSError; 338, argument_list; 338, 339; 339, binary_operator:+; 339, 340; 339, 341; 340, identifier:nodesAtrName; 341, string:" already exists"; 342, expression_statement; 342, 343; 343, call; 343, 344; 343, 345; 344, identifier:writeEdgeList; 345, argument_list; 345, 346; 345, 347; 345, 348; 345, 351; 345, 354; 346, identifier:grph; 347, identifier:edgeListName; 348, keyword_argument; 348, 349; 348, 350; 349, identifier:extraInfo; 350, identifier:edgeInfo; 351, keyword_argument; 351, 352; 351, 353; 352, identifier:allSameAttribute; 353, identifier:allSameAttribute; 354, keyword_argument; 354, 355; 354, 356; 355, identifier:_progBar; 356, identifier:PBar; 357, expression_statement; 357, 358; 358, call; 358, 359; 358, 360; 359, identifier:writeNodeAttributeFile; 360, argument_list; 360, 361; 360, 362; 360, 363; 360, 366; 361, identifier:grph; 362, identifier:nodesAtrName; 363, keyword_argument; 363, 364; 363, 365; 364, identifier:allSameAttribute; 365, identifier:allSameAttribute; 366, keyword_argument; 366, 367; 366, 368; 367, identifier:_progBar; 368, identifier:PBar; 369, expression_statement; 369, 370; 370, call; 370, 371; 370, 374; 371, attribute; 371, 372; 371, 373; 372, identifier:PBar; 373, identifier:finish; 374, argument_list; 374, 375; 375, call; 375, 376; 375, 379; 376, attribute; 376, 377; 376, 378; 377, string:"{} nodes and {} edges written to file"; 378, identifier:format; 379, argument_list; 379, 380; 379, 388; 380, call; 380, 381; 380, 382; 381, identifier:len; 382, argument_list; 382, 383; 383, call; 383, 384; 383, 387; 384, attribute; 384, 385; 384, 386; 385, identifier:grph; 386, identifier:nodes; 387, argument_list; 388, call; 388, 389; 388, 390; 389, identifier:len; 390, argument_list; 390, 391; 391, call; 391, 392; 391, 395; 392, attribute; 392, 393; 392, 394; 393, identifier:grph; 394, identifier:edges; 395, argument_list
def writeGraph(grph, name, edgeInfo = True, typing = False, suffix = 'csv', overwrite = True, allSameAttribute = False): """Writes both the edge list and the node attribute list of _grph_ to files starting with _name_. The output files start with _name_, the file type (edgeList, nodeAttributes) then if typing is True the type of graph (directed or undirected) then the suffix, the default is as follows: >> name_fileType.suffix Both files are csv's with comma delimiters and double quote quoting characters. The edge list has two columns for the source and destination of the edge, `'From'` and `'To'` respectively, then, if _edgeInfo_ is `True`, for each attribute of the node another column is created. The node list has one column call "ID" with the node ids used by networkx and all other columns are the node attributes. To read back these files use [readGraph()](#metaknowledge.graphHelpers.readGraph) and to write only one type of lsit use [writeEdgeList()](#metaknowledge.graphHelpers.writeEdgeList) or [writeNodeAttributeFile()](#metaknowledge.graphHelpers.writeNodeAttributeFile). **Warning**: this function will overwrite files, if they are in the way of the output, to prevent this set _overwrite_ to `False` **Note**: If any nodes or edges are missing an attribute a `KeyError` will be raised. # Parameters _grph_ : `networkx Graph` > A networkx graph of the network to be written. _name_ : `str` > The start of the file name to be written, can include a path. _edgeInfo_ : `optional [bool]` > Default `True`, if `True` the the attributes of each edge are written to the edge list. _typing_ : `optional [bool]` > Default `False`, if `True` the directed ness of the graph will be added to the file names. _suffix_ : `optional [str]` > Default `"csv"`, the suffix of the file. _overwrite_ : `optional [bool]` > Default `True`, if `True` files will be overwritten silently, otherwise an `OSError` exception will be raised. """ progArgs = (0, "Writing the graph to files starting with: {}".format(name)) if metaknowledge.VERBOSE_MODE: progKwargs = {'dummy' : False} else: progKwargs = {'dummy' : True} with _ProgressBar(*progArgs, **progKwargs) as PBar: if typing: if isinstance(grph, nx.classes.digraph.DiGraph) or isinstance(grph, nx.classes.multidigraph.MultiDiGraph): grphType = "_directed" else: grphType = "_undirected" else: grphType = '' nameCompts = os.path.split(os.path.expanduser(os.path.normpath(name))) if nameCompts[0] == '' and nameCompts[1] == '': edgeListName = "edgeList"+ grphType + '.' + suffix nodesAtrName = "nodeAttributes"+ grphType + '.' + suffix elif nameCompts[0] == '': edgeListName = nameCompts[1] + "_edgeList"+ grphType + '.' + suffix nodesAtrName = nameCompts[1] + "_nodeAttributes"+ grphType + '.' + suffix elif nameCompts[1] == '': edgeListName = os.path.join(nameCompts[0], "edgeList"+ grphType + '.' + suffix) nodesAtrName = os.path.join(nameCompts[0], "nodeAttributes"+ grphType + '.' + suffix) else: edgeListName = os.path.join(nameCompts[0], nameCompts[1] + "_edgeList"+ grphType + '.' + suffix) nodesAtrName = os.path.join(nameCompts[0], nameCompts[1] + "_nodeAttributes"+ grphType + '.' + suffix) if not overwrite: if os.path.isfile(edgeListName): raise OSError(edgeListName+ " already exists") if os.path.isfile(nodesAtrName): raise OSError(nodesAtrName + " already exists") writeEdgeList(grph, edgeListName, extraInfo = edgeInfo, allSameAttribute = allSameAttribute, _progBar = PBar) writeNodeAttributeFile(grph, nodesAtrName, allSameAttribute = allSameAttribute, _progBar = PBar) PBar.finish("{} nodes and {} edges written to file".format(len(grph.nodes()), len(grph.edges())))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:mergeGraphs; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:targetGraph; 5, identifier:addedGraph; 6, default_parameter; 6, 7; 6, 8; 7, identifier:incrementedNodeVal; 8, string:'count'; 9, default_parameter; 9, 10; 9, 11; 10, identifier:incrementedEdgeVal; 11, string:'weight'; 12, block; 12, 13; 12, 15; 12, 77; 13, expression_statement; 13, 14; 14, comment; 15, for_statement; 15, 16; 15, 19; 15, 27; 16, pattern_list; 16, 17; 16, 18; 17, identifier:addedNode; 18, identifier:attribs; 19, call; 19, 20; 19, 23; 20, attribute; 20, 21; 20, 22; 21, identifier:addedGraph; 22, identifier:nodes; 23, argument_list; 23, 24; 24, keyword_argument; 24, 25; 24, 26; 25, identifier:data; 26, True; 27, block; 27, 28; 28, if_statement; 28, 29; 28, 30; 28, 57; 29, identifier:incrementedNodeVal; 30, block; 30, 31; 31, try_statement; 31, 32; 31, 45; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, augmented_assignment:+=; 34, 35; 34, 42; 35, subscript; 35, 36; 35, 41; 36, subscript; 36, 37; 36, 40; 37, attribute; 37, 38; 37, 39; 38, identifier:targetGraph; 39, identifier:node; 40, identifier:addedNode; 41, identifier:incrementedNodeVal; 42, subscript; 42, 43; 42, 44; 43, identifier:attribs; 44, identifier:incrementedNodeVal; 45, except_clause; 45, 46; 45, 47; 46, identifier:KeyError; 47, block; 47, 48; 48, expression_statement; 48, 49; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:targetGraph; 52, identifier:add_node; 53, argument_list; 53, 54; 53, 55; 54, identifier:addedNode; 55, dictionary_splat; 55, 56; 56, identifier:attribs; 57, else_clause; 57, 58; 58, block; 58, 59; 59, if_statement; 59, 60; 59, 67; 60, not_operator; 60, 61; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:targetGraph; 64, identifier:has_node; 65, argument_list; 65, 66; 66, identifier:addedNode; 67, block; 67, 68; 68, expression_statement; 68, 69; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:targetGraph; 72, identifier:add_node; 73, argument_list; 73, 74; 73, 75; 74, identifier:addedNode; 75, dictionary_splat; 75, 76; 76, identifier:attribs; 77, for_statement; 77, 78; 77, 82; 77, 90; 78, pattern_list; 78, 79; 78, 80; 78, 81; 79, identifier:edgeNode1; 80, identifier:edgeNode2; 81, identifier:attribs; 82, call; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:addedGraph; 85, identifier:edges; 86, argument_list; 86, 87; 87, keyword_argument; 87, 88; 87, 89; 88, identifier:data; 89, True; 90, block; 90, 91; 91, if_statement; 91, 92; 91, 93; 91, 122; 92, identifier:incrementedEdgeVal; 93, block; 93, 94; 94, try_statement; 94, 95; 94, 109; 95, block; 95, 96; 96, expression_statement; 96, 97; 97, augmented_assignment:+=; 97, 98; 97, 106; 98, subscript; 98, 99; 98, 105; 99, subscript; 99, 100; 99, 103; 99, 104; 100, attribute; 100, 101; 100, 102; 101, identifier:targetGraph; 102, identifier:edges; 103, identifier:edgeNode1; 104, identifier:edgeNode2; 105, identifier:incrementedEdgeVal; 106, subscript; 106, 107; 106, 108; 107, identifier:attribs; 108, identifier:incrementedEdgeVal; 109, except_clause; 109, 110; 109, 111; 110, identifier:KeyError; 111, block; 111, 112; 112, expression_statement; 112, 113; 113, call; 113, 114; 113, 117; 114, attribute; 114, 115; 114, 116; 115, identifier:targetGraph; 116, identifier:add_edge; 117, argument_list; 117, 118; 117, 119; 117, 120; 118, identifier:edgeNode1; 119, identifier:edgeNode2; 120, dictionary_splat; 120, 121; 121, identifier:attribs; 122, else_clause; 122, 123; 123, block; 123, 124; 124, if_statement; 124, 125; 124, 135; 125, not_operator; 125, 126; 126, call; 126, 127; 126, 132; 127, attribute; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:targetGraph; 130, identifier:Graph; 131, identifier:has_edge; 132, argument_list; 132, 133; 132, 134; 133, identifier:edgeNode1; 134, identifier:edgeNode2; 135, block; 135, 136; 136, expression_statement; 136, 137; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:targetGraph; 140, identifier:add_edge; 141, argument_list; 141, 142; 141, 143; 141, 144; 142, identifier:edgeNode1; 143, identifier:edgeNode2; 144, dictionary_splat; 144, 145; 145, identifier:attribs
def mergeGraphs(targetGraph, addedGraph, incrementedNodeVal = 'count', incrementedEdgeVal = 'weight'): """A quick way of merging graphs, this is meant to be quick and is only intended for graphs generated by metaknowledge. This does not check anything and as such may cause unexpected results if the source and target were not generated by the same method. **mergeGraphs**() will **modify** _targetGraph_ in place by adding the nodes and edges found in the second, _addedGraph_. If a node or edge exists _targetGraph_ is given precedence, but the edge and node attributes given by _incrementedNodeVal_ and incrementedEdgeVal are added instead of being overwritten. # Parameters _targetGraph_ : `networkx Graph` > the graph to be modified, it has precedence. _addedGraph_ : `networkx Graph` > the graph that is unmodified, it is added and does **not** have precedence. _incrementedNodeVal_ : `optional [str]` > default `'count'`, the name of the count attribute for the graph's nodes. When merging this attribute will be the sum of the values in the input graphs, instead of _targetGraph_'s value. _incrementedEdgeVal_ : `optional [str]` > default `'weight'`, the name of the weight attribute for the graph's edges. When merging this attribute will be the sum of the values in the input graphs, instead of _targetGraph_'s value. """ for addedNode, attribs in addedGraph.nodes(data = True): if incrementedNodeVal: try: targetGraph.node[addedNode][incrementedNodeVal] += attribs[incrementedNodeVal] except KeyError: targetGraph.add_node(addedNode, **attribs) else: if not targetGraph.has_node(addedNode): targetGraph.add_node(addedNode, **attribs) for edgeNode1, edgeNode2, attribs in addedGraph.edges(data = True): if incrementedEdgeVal: try: targetGraph.edges[edgeNode1, edgeNode2][incrementedEdgeVal] += attribs[incrementedEdgeVal] except KeyError: targetGraph.add_edge(edgeNode1, edgeNode2, **attribs) else: if not targetGraph.Graph.has_edge(edgeNode1, edgeNode2): targetGraph.add_edge(edgeNode1, edgeNode2, **attribs)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:writeRecord; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:f; 6, block; 6, 7; 6, 9; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 13; 9, 29; 10, attribute; 10, 11; 10, 12; 11, identifier:self; 12, identifier:bad; 13, block; 13, 14; 14, raise_statement; 14, 15; 15, call; 15, 16; 15, 17; 16, identifier:BadPubmedRecord; 17, argument_list; 17, 18; 18, call; 18, 19; 18, 22; 19, attribute; 19, 20; 19, 21; 20, string:"This record cannot be converted to a file as the input was malformed.\nThe original line number (if any) is: {} and the original file is: '{}'"; 21, identifier:format; 22, argument_list; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:self; 25, identifier:_sourceLine; 26, attribute; 26, 27; 26, 28; 27, identifier:self; 28, identifier:_sourceFile; 29, else_clause; 29, 30; 30, block; 30, 31; 30, 35; 30, 145; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:authTags; 34, dictionary; 35, for_statement; 35, 36; 35, 37; 35, 38; 36, identifier:tag; 37, identifier:authorBasedTags; 38, block; 38, 39; 39, for_statement; 39, 40; 39, 41; 39, 50; 40, identifier:val; 41, call; 41, 42; 41, 47; 42, attribute; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:self; 45, identifier:_fieldDict; 46, identifier:get; 47, argument_list; 47, 48; 47, 49; 48, identifier:tag; 49, list:[]; 50, block; 50, 51; 50, 60; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:split; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:val; 57, identifier:split; 58, argument_list; 58, 59; 59, string:' : '; 60, try_statement; 60, 61; 60, 103; 61, block; 61, 62; 62, expression_statement; 62, 63; 63, call; 63, 64; 63, 71; 64, attribute; 64, 65; 64, 70; 65, subscript; 65, 66; 65, 67; 66, identifier:authTags; 67, subscript; 67, 68; 67, 69; 68, identifier:split; 69, integer:0; 70, identifier:append; 71, argument_list; 71, 72; 72, call; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, string:"{0}{1}- {2}\n"; 75, identifier:format; 76, argument_list; 76, 77; 76, 78; 76, 87; 77, identifier:tag; 78, binary_operator:*; 78, 79; 78, 80; 79, string:' '; 80, parenthesized_expression; 80, 81; 81, binary_operator:-; 81, 82; 81, 83; 82, integer:4; 83, call; 83, 84; 83, 85; 84, identifier:len; 85, argument_list; 85, 86; 86, identifier:tag; 87, call; 87, 88; 87, 100; 88, attribute; 88, 89; 88, 99; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, string:' : '; 92, identifier:join; 93, argument_list; 93, 94; 94, subscript; 94, 95; 94, 96; 95, identifier:split; 96, slice; 96, 97; 96, 98; 97, integer:1; 98, colon; 99, identifier:replace; 100, argument_list; 100, 101; 100, 102; 101, string:'\n'; 102, string:'\n '; 103, except_clause; 103, 104; 103, 105; 104, identifier:KeyError; 105, block; 105, 106; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 113; 108, subscript; 108, 109; 108, 110; 109, identifier:authTags; 110, subscript; 110, 111; 110, 112; 111, identifier:split; 112, integer:0; 113, list:["{0}{1}- {2}\n".format(tag, ' ' * (4 - len(tag)),' : '.join(split[1:]).replace('\n', '\n '))]; 113, 114; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, string:"{0}{1}- {2}\n"; 117, identifier:format; 118, argument_list; 118, 119; 118, 120; 118, 129; 119, identifier:tag; 120, binary_operator:*; 120, 121; 120, 122; 121, string:' '; 122, parenthesized_expression; 122, 123; 123, binary_operator:-; 123, 124; 123, 125; 124, integer:4; 125, call; 125, 126; 125, 127; 126, identifier:len; 127, argument_list; 127, 128; 128, identifier:tag; 129, call; 129, 130; 129, 142; 130, attribute; 130, 131; 130, 141; 131, call; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, string:' : '; 134, identifier:join; 135, argument_list; 135, 136; 136, subscript; 136, 137; 136, 138; 137, identifier:split; 138, slice; 138, 139; 138, 140; 139, integer:1; 140, colon; 141, identifier:replace; 142, argument_list; 142, 143; 142, 144; 143, string:'\n'; 144, string:'\n '; 145, for_statement; 145, 146; 145, 149; 145, 156; 146, pattern_list; 146, 147; 146, 148; 147, identifier:tag; 148, identifier:value; 149, call; 149, 150; 149, 155; 150, attribute; 150, 151; 150, 154; 151, attribute; 151, 152; 151, 153; 152, identifier:self; 153, identifier:_fieldDict; 154, identifier:items; 155, argument_list; 156, block; 156, 157; 157, if_statement; 157, 158; 157, 161; 157, 163; 158, comparison_operator:in; 158, 159; 158, 160; 159, identifier:tag; 160, identifier:authorBasedTags; 161, block; 161, 162; 162, continue_statement; 163, else_clause; 163, 164; 164, block; 164, 165; 165, for_statement; 165, 166; 165, 167; 165, 168; 166, identifier:v; 167, identifier:value; 168, block; 168, 169; 168, 197; 169, expression_statement; 169, 170; 170, call; 170, 171; 170, 174; 171, attribute; 171, 172; 171, 173; 172, identifier:f; 173, identifier:write; 174, argument_list; 174, 175; 175, call; 175, 176; 175, 179; 176, attribute; 176, 177; 176, 178; 177, string:"{0}{1}- {2}\n"; 178, identifier:format; 179, argument_list; 179, 180; 179, 181; 179, 190; 180, identifier:tag; 181, binary_operator:*; 181, 182; 181, 183; 182, string:' '; 183, parenthesized_expression; 183, 184; 184, binary_operator:-; 184, 185; 184, 186; 185, integer:4; 186, call; 186, 187; 186, 188; 187, identifier:len; 188, argument_list; 188, 189; 189, identifier:tag; 190, call; 190, 191; 190, 194; 191, attribute; 191, 192; 191, 193; 192, identifier:v; 193, identifier:replace; 194, argument_list; 194, 195; 194, 196; 195, string:'\n'; 196, string:'\n '; 197, if_statement; 197, 198; 197, 201; 198, comparison_operator:==; 198, 199; 198, 200; 199, identifier:tag; 200, string:'AU'; 201, block; 201, 202; 202, for_statement; 202, 203; 202, 204; 202, 211; 203, identifier:authVal; 204, call; 204, 205; 204, 208; 205, attribute; 205, 206; 205, 207; 206, identifier:authTags; 207, identifier:get; 208, argument_list; 208, 209; 208, 210; 209, identifier:v; 210, list:[]; 211, block; 211, 212; 212, expression_statement; 212, 213; 213, call; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:f; 216, identifier:write; 217, argument_list; 217, 218; 218, identifier:authVal
def writeRecord(self, f): """This is nearly identical to the original the FAU tag is the only tag not writen in the same place, doing so would require changing the parser and lots of extra logic. """ if self.bad: raise BadPubmedRecord("This record cannot be converted to a file as the input was malformed.\nThe original line number (if any) is: {} and the original file is: '{}'".format(self._sourceLine, self._sourceFile)) else: authTags = {} for tag in authorBasedTags: for val in self._fieldDict.get(tag, []): split = val.split(' : ') try: authTags[split[0]].append("{0}{1}- {2}\n".format(tag, ' ' * (4 - len(tag)),' : '.join(split[1:]).replace('\n', '\n '))) except KeyError: authTags[split[0]] = ["{0}{1}- {2}\n".format(tag, ' ' * (4 - len(tag)),' : '.join(split[1:]).replace('\n', '\n '))] for tag, value in self._fieldDict.items(): if tag in authorBasedTags: continue else: for v in value: f.write("{0}{1}- {2}\n".format(tag, ' ' * (4 - len(tag)), v.replace('\n', '\n '))) if tag == 'AU': for authVal in authTags.get(v,[]): f.write(authVal)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 32; 2, function_name:graphDensityContourPlot; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 3, 29; 4, identifier:G; 5, default_parameter; 5, 6; 5, 7; 6, identifier:iters; 7, integer:50; 8, default_parameter; 8, 9; 8, 10; 9, identifier:layout; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:layoutScaleFactor; 13, integer:1; 14, default_parameter; 14, 15; 14, 16; 15, identifier:overlay; 16, False; 17, default_parameter; 17, 18; 17, 19; 18, identifier:nodeSize; 19, integer:10; 20, default_parameter; 20, 21; 20, 22; 21, identifier:axisSamples; 22, integer:100; 23, default_parameter; 23, 24; 23, 25; 24, identifier:blurringFactor; 25, float:.1; 26, default_parameter; 26, 27; 26, 28; 27, identifier:contours; 28, integer:15; 29, default_parameter; 29, 30; 29, 31; 30, identifier:graphType; 31, string:'coloured'; 32, block; 32, 33; 32, 35; 32, 41; 32, 81; 32, 260; 32, 268; 32, 269; 32, 280; 32, 305; 32, 321; 32, 334; 32, 346; 32, 376; 32, 383; 32, 390; 33, expression_statement; 33, 34; 34, comment; 35, import_from_statement; 35, 36; 35, 39; 36, dotted_name; 36, 37; 36, 38; 37, identifier:mpl_toolkits; 38, identifier:mplot3d; 39, dotted_name; 39, 40; 40, identifier:Axes3D; 41, if_statement; 41, 42; 41, 67; 42, boolean_operator:and; 42, 43; 42, 55; 43, not_operator; 43, 44; 44, call; 44, 45; 44, 46; 45, identifier:isinstance; 46, argument_list; 46, 47; 46, 48; 47, identifier:G; 48, attribute; 48, 49; 48, 54; 49, attribute; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:nx; 52, identifier:classes; 53, identifier:digraph; 54, identifier:DiGraph; 55, not_operator; 55, 56; 56, call; 56, 57; 56, 58; 57, identifier:isinstance; 58, argument_list; 58, 59; 58, 60; 59, identifier:G; 60, attribute; 60, 61; 60, 66; 61, attribute; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:nx; 64, identifier:classes; 65, identifier:graph; 66, identifier:Graph; 67, block; 67, 68; 68, raise_statement; 68, 69; 69, call; 69, 70; 69, 71; 70, identifier:TypeError; 71, argument_list; 71, 72; 72, call; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, string:"{} is not a valid input."; 75, identifier:format; 76, argument_list; 76, 77; 77, call; 77, 78; 77, 79; 78, identifier:type; 79, argument_list; 79, 80; 80, identifier:G; 81, if_statement; 81, 82; 81, 85; 81, 155; 81, 245; 82, comparison_operator:is; 82, 83; 82, 84; 83, identifier:layout; 84, None; 85, block; 85, 86; 85, 103; 85, 119; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:layout; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:nx; 92, identifier:spring_layout; 93, argument_list; 93, 94; 93, 95; 93, 100; 94, identifier:G; 95, keyword_argument; 95, 96; 95, 97; 96, identifier:scale; 97, binary_operator:-; 97, 98; 97, 99; 98, identifier:axisSamples; 99, integer:1; 100, keyword_argument; 100, 101; 100, 102; 101, identifier:iterations; 102, identifier:iters; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:grid; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:np; 109, identifier:zeros; 110, argument_list; 110, 111; 110, 114; 111, list:[axisSamples, axisSamples]; 111, 112; 111, 113; 112, identifier:axisSamples; 113, identifier:axisSamples; 114, keyword_argument; 114, 115; 114, 116; 115, identifier:dtype; 116, attribute; 116, 117; 116, 118; 117, identifier:np; 118, identifier:float32; 119, for_statement; 119, 120; 119, 121; 119, 126; 120, identifier:v; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:layout; 124, identifier:values; 125, argument_list; 126, block; 126, 127; 126, 147; 127, expression_statement; 127, 128; 128, assignment; 128, 129; 128, 132; 129, pattern_list; 129, 130; 129, 131; 130, identifier:x; 131, identifier:y; 132, call; 132, 133; 132, 134; 133, identifier:tuple; 134, generator_expression; 134, 135; 134, 139; 135, call; 135, 136; 135, 137; 136, identifier:int; 137, argument_list; 137, 138; 138, identifier:x; 139, for_in_clause; 139, 140; 139, 141; 140, identifier:x; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:v; 144, identifier:round; 145, argument_list; 145, 146; 146, integer:0; 147, expression_statement; 147, 148; 148, augmented_assignment:+=; 148, 149; 148, 154; 149, subscript; 149, 150; 149, 153; 150, subscript; 150, 151; 150, 152; 151, identifier:grid; 152, identifier:y; 153, identifier:x; 154, integer:1; 155, elif_clause; 155, 156; 155, 161; 156, call; 156, 157; 156, 158; 157, identifier:isinstance; 158, argument_list; 158, 159; 158, 160; 159, identifier:layout; 160, identifier:dict; 161, block; 161, 162; 161, 170; 161, 186; 161, 195; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:layout; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:layout; 168, identifier:copy; 169, argument_list; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:grid; 173, call; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:np; 176, identifier:zeros; 177, argument_list; 177, 178; 177, 181; 178, list:[axisSamples, axisSamples]; 178, 179; 178, 180; 179, identifier:axisSamples; 180, identifier:axisSamples; 181, keyword_argument; 181, 182; 181, 183; 182, identifier:dtype; 183, attribute; 183, 184; 183, 185; 184, identifier:np; 185, identifier:float32; 186, expression_statement; 186, 187; 187, assignment; 187, 188; 187, 189; 188, identifier:multFactor; 189, binary_operator:/; 189, 190; 189, 194; 190, parenthesized_expression; 190, 191; 191, binary_operator:-; 191, 192; 191, 193; 192, identifier:axisSamples; 193, integer:1; 194, identifier:layoutScaleFactor; 195, for_statement; 195, 196; 195, 197; 195, 202; 196, identifier:k; 197, call; 197, 198; 197, 201; 198, attribute; 198, 199; 198, 200; 199, identifier:layout; 200, identifier:keys; 201, argument_list; 202, block; 202, 203; 202, 211; 202, 217; 202, 237; 203, expression_statement; 203, 204; 204, assignment; 204, 205; 204, 206; 205, identifier:tmpPos; 206, binary_operator:*; 206, 207; 206, 210; 207, subscript; 207, 208; 207, 209; 208, identifier:layout; 209, identifier:k; 210, identifier:multFactor; 211, expression_statement; 211, 212; 212, assignment; 212, 213; 212, 216; 213, subscript; 213, 214; 213, 215; 214, identifier:layout; 215, identifier:k; 216, identifier:tmpPos; 217, expression_statement; 217, 218; 218, assignment; 218, 219; 218, 222; 219, pattern_list; 219, 220; 219, 221; 220, identifier:x; 221, identifier:y; 222, call; 222, 223; 222, 224; 223, identifier:tuple; 224, generator_expression; 224, 225; 224, 229; 225, call; 225, 226; 225, 227; 226, identifier:int; 227, argument_list; 227, 228; 228, identifier:x; 229, for_in_clause; 229, 230; 229, 231; 230, identifier:x; 231, call; 231, 232; 231, 235; 232, attribute; 232, 233; 232, 234; 233, identifier:tmpPos; 234, identifier:round; 235, argument_list; 235, 236; 236, integer:0; 237, expression_statement; 237, 238; 238, augmented_assignment:+=; 238, 239; 238, 244; 239, subscript; 239, 240; 239, 243; 240, subscript; 240, 241; 240, 242; 241, identifier:grid; 242, identifier:y; 243, identifier:x; 244, integer:1; 245, else_clause; 245, 246; 246, block; 246, 247; 247, raise_statement; 247, 248; 248, call; 248, 249; 248, 250; 249, identifier:TypeError; 250, argument_list; 250, 251; 251, call; 251, 252; 251, 255; 252, attribute; 252, 253; 252, 254; 253, string:"{} is not a valid input."; 254, identifier:format; 255, argument_list; 255, 256; 256, call; 256, 257; 256, 258; 257, identifier:type; 258, argument_list; 258, 259; 259, identifier:layout; 260, expression_statement; 260, 261; 261, assignment; 261, 262; 261, 263; 262, identifier:fig; 263, call; 263, 264; 263, 267; 264, attribute; 264, 265; 264, 266; 265, identifier:plt; 266, identifier:figure; 267, argument_list; 268, comment; 269, expression_statement; 269, 270; 270, assignment; 270, 271; 270, 272; 271, identifier:axis; 272, call; 272, 273; 272, 276; 273, attribute; 273, 274; 273, 275; 274, identifier:fig; 275, identifier:gca; 276, argument_list; 276, 277; 277, keyword_argument; 277, 278; 277, 279; 278, identifier:projection; 279, string:'3d'; 280, if_statement; 280, 281; 280, 282; 281, identifier:overlay; 282, block; 282, 283; 283, expression_statement; 283, 284; 284, call; 284, 285; 284, 288; 285, attribute; 285, 286; 285, 287; 286, identifier:nx; 287, identifier:draw_networkx; 288, argument_list; 288, 289; 288, 290; 288, 293; 288, 296; 288, 299; 288, 302; 289, identifier:G; 290, keyword_argument; 290, 291; 290, 292; 291, identifier:pos; 292, identifier:layout; 293, keyword_argument; 293, 294; 293, 295; 294, identifier:ax; 295, identifier:axis; 296, keyword_argument; 296, 297; 296, 298; 297, identifier:node_size; 298, identifier:nodeSize; 299, keyword_argument; 299, 300; 299, 301; 300, identifier:with_labels; 301, False; 302, keyword_argument; 302, 303; 302, 304; 303, identifier:edgelist; 304, list:[]; 305, expression_statement; 305, 306; 306, assignment; 306, 307; 306, 308; 307, identifier:grid; 308, call; 308, 309; 308, 312; 309, attribute; 309, 310; 309, 311; 310, identifier:ndi; 311, identifier:gaussian_filter; 312, argument_list; 312, 313; 312, 314; 313, identifier:grid; 314, tuple; 314, 315; 314, 318; 315, binary_operator:*; 315, 316; 315, 317; 316, identifier:blurringFactor; 317, identifier:axisSamples; 318, binary_operator:*; 318, 319; 318, 320; 319, identifier:blurringFactor; 320, identifier:axisSamples; 321, expression_statement; 321, 322; 322, assignment; 322, 323; 322, 324; 323, identifier:X; 324, assignment; 324, 325; 324, 326; 325, identifier:Y; 326, call; 326, 327; 326, 330; 327, attribute; 327, 328; 327, 329; 328, identifier:np; 329, identifier:arange; 330, argument_list; 330, 331; 330, 332; 330, 333; 331, integer:0; 332, identifier:axisSamples; 333, integer:1; 334, expression_statement; 334, 335; 335, assignment; 335, 336; 335, 339; 336, pattern_list; 336, 337; 336, 338; 337, identifier:X; 338, identifier:Y; 339, call; 339, 340; 339, 343; 340, attribute; 340, 341; 340, 342; 341, identifier:np; 342, identifier:meshgrid; 343, argument_list; 343, 344; 343, 345; 344, identifier:X; 345, identifier:Y; 346, if_statement; 346, 347; 346, 350; 346, 362; 347, comparison_operator:==; 347, 348; 347, 349; 348, identifier:graphType; 349, string:"solid"; 350, block; 350, 351; 351, expression_statement; 351, 352; 352, assignment; 352, 353; 352, 354; 353, identifier:CS; 354, call; 354, 355; 354, 358; 355, attribute; 355, 356; 355, 357; 356, identifier:axis; 357, identifier:plot_surface; 358, argument_list; 358, 359; 358, 360; 358, 361; 359, identifier:X; 360, identifier:Y; 361, identifier:grid; 362, else_clause; 362, 363; 363, block; 363, 364; 364, expression_statement; 364, 365; 365, assignment; 365, 366; 365, 367; 366, identifier:CS; 367, call; 367, 368; 367, 371; 368, attribute; 368, 369; 368, 370; 369, identifier:axis; 370, identifier:contourf; 371, argument_list; 371, 372; 371, 373; 371, 374; 371, 375; 372, identifier:X; 373, identifier:Y; 374, identifier:grid; 375, identifier:contours; 376, expression_statement; 376, 377; 377, call; 377, 378; 377, 381; 378, attribute; 378, 379; 378, 380; 379, identifier:axis; 380, identifier:set_xlabel; 381, argument_list; 381, 382; 382, string:'X'; 383, expression_statement; 383, 384; 384, call; 384, 385; 384, 388; 385, attribute; 385, 386; 385, 387; 386, identifier:axis; 387, identifier:set_ylabel; 388, argument_list; 388, 389; 389, string:'Y'; 390, expression_statement; 390, 391; 391, call; 391, 392; 391, 395; 392, attribute; 392, 393; 392, 394; 393, identifier:axis; 394, identifier:set_zlabel; 395, argument_list; 395, 396; 396, string:'Node Density'
def graphDensityContourPlot(G, iters = 50, layout = None, layoutScaleFactor = 1, overlay = False, nodeSize = 10, axisSamples = 100, blurringFactor = .1, contours = 15, graphType = 'coloured'): """Creates a 3D plot giving the density of nodes on a 2D plane, as a surface in 3D. Most of the options are for tweaking the final appearance. _layout_ and _layoutScaleFactor_ allow a pre-layout graph to be provided. If a layout is not provided the [networkx.spring_layout()](https://networkx.github.io/documentation/latest/reference/generated/networkx.drawing.layout.spring_layout.html) is used after _iters_ iterations. Then, once the graph has been laid out a grid of _axisSamples_ cells by _axisSamples_ cells is overlaid and the number of nodes in each cell is determined, a gaussian blur is then applied with a sigma of _blurringFactor_. This then forms a surface in 3 dimensions, which is then plotted. If you find the resultant image looks too banded raise the the _contours_ number to ~50. # Parameters _G_ : `networkx Graph` > The graph to be plotted _iters_ : `optional [int]` > Default `50`, the number of iterations for the spring layout if _layout_ is not provided. _layout_ : `optional [networkx layout dictionary]` > Default `None`, if provided will be used as a layout of the graph, the maximum distance from the origin along any axis must also given as _layoutScaleFactor_, which is by default `1`. _layoutScaleFactor_ : `optional [double]` > Default `1`, The maximum distance from the origin allowed along any axis given by _layout_, i.e. the layout must fit in a square centered at the origin with side lengths 2 * _layoutScaleFactor_ _overlay_ : `optional [bool]` > Default `False`, if `True` the 2D graph will be plotted on the X-Y plane at Z = 0. _nodeSize_ : `optional [double]` > Default `10`, the size of the nodes dawn in the overlay _axisSamples_ : `optional [int]` > Default 100, the number of cells used along each axis for sampling. A larger number will mean a lower average density. _blurringFactor_ : `optional [double]` > Default `0.1`, the sigma value used for smoothing the surface density. The higher this number the smoother the surface. _contours_ : `optional [int]` > Default 15, the number of different heights drawn. If this number is low the resultant image will look very banded. It is recommended this be raised above `50` if you want your images to look good, **Warning** this will make them much slower to generate and interact with. _graphType_ : `optional [str]` > Default `'coloured'`, if `'coloured'` the image will have a destiny based colourization applied, the only other option is `'solid'` which removes the colourization. """ from mpl_toolkits.mplot3d import Axes3D if not isinstance(G, nx.classes.digraph.DiGraph) and not isinstance(G, nx.classes.graph.Graph): raise TypeError("{} is not a valid input.".format(type(G))) if layout is None: layout = nx.spring_layout(G, scale = axisSamples - 1, iterations = iters) grid = np.zeros( [axisSamples, axisSamples],dtype=np.float32) for v in layout.values(): x, y = tuple(int(x) for x in v.round(0)) grid[y][x] += 1 elif isinstance(layout, dict): layout = layout.copy() grid = np.zeros([axisSamples, axisSamples],dtype=np.float32) multFactor = (axisSamples - 1) / layoutScaleFactor for k in layout.keys(): tmpPos = layout[k] * multFactor layout[k] = tmpPos x, y = tuple(int(x) for x in tmpPos.round(0)) grid[y][x] += 1 else: raise TypeError("{} is not a valid input.".format(type(layout))) fig = plt.figure() #axis = fig.add_subplot(111) axis = fig.gca(projection='3d') if overlay: nx.draw_networkx(G, pos = layout, ax = axis, node_size = nodeSize, with_labels = False, edgelist = []) grid = ndi.gaussian_filter(grid, (blurringFactor * axisSamples, blurringFactor * axisSamples)) X = Y = np.arange(0, axisSamples, 1) X, Y = np.meshgrid(X, Y) if graphType == "solid": CS = axis.plot_surface(X,Y, grid) else: CS = axis.contourf(X, Y, grid, contours) axis.set_xlabel('X') axis.set_ylabel('Y') axis.set_zlabel('Node Density')
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:makeNodeTuple; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 4, identifier:citation; 5, identifier:idVal; 6, identifier:nodeInfo; 7, identifier:fullInfo; 8, identifier:nodeType; 9, identifier:count; 10, identifier:coreCitesDict; 11, identifier:coreValues; 12, identifier:detailedValues; 13, identifier:addCR; 14, block; 14, 15; 14, 17; 14, 21; 14, 306; 14, 318; 14, 327; 15, expression_statement; 15, 16; 16, comment; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:d; 20, dictionary; 21, if_statement; 21, 22; 21, 23; 22, identifier:nodeInfo; 23, block; 23, 24; 24, if_statement; 24, 25; 24, 28; 24, 251; 24, 284; 24, 298; 25, comparison_operator:==; 25, 26; 25, 27; 26, identifier:nodeType; 27, string:'full'; 28, block; 28, 29; 29, if_statement; 29, 30; 29, 31; 29, 239; 30, identifier:coreValues; 31, block; 31, 32; 32, if_statement; 32, 33; 32, 36; 32, 206; 33, comparison_operator:in; 33, 34; 33, 35; 34, identifier:citation; 35, identifier:coreCitesDict; 36, block; 36, 37; 36, 43; 36, 51; 36, 173; 36, 179; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:R; 40, subscript; 40, 41; 40, 42; 41, identifier:coreCitesDict; 42, identifier:citation; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 48; 45, subscript; 45, 46; 45, 47; 46, identifier:d; 47, string:'MK-ID'; 48, attribute; 48, 49; 48, 50; 49, identifier:R; 50, identifier:id; 51, if_statement; 51, 52; 51, 54; 51, 128; 52, not_operator; 52, 53; 53, identifier:detailedValues; 54, block; 54, 55; 54, 59; 54, 117; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:infoVals; 58, list:[]; 59, for_statement; 59, 60; 59, 61; 59, 62; 60, identifier:tag; 61, identifier:coreValues; 62, block; 62, 63; 62, 72; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:tagVal; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:R; 69, identifier:get; 70, argument_list; 70, 71; 71, identifier:tag; 72, if_statement; 72, 73; 72, 78; 72, 92; 72, 114; 73, call; 73, 74; 73, 75; 74, identifier:isinstance; 75, argument_list; 75, 76; 75, 77; 76, identifier:tagVal; 77, identifier:str; 78, block; 78, 79; 79, expression_statement; 79, 80; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:infoVals; 83, identifier:append; 84, argument_list; 84, 85; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:tagVal; 88, identifier:replace; 89, argument_list; 89, 90; 89, 91; 90, string:','; 91, string:''; 92, elif_clause; 92, 93; 92, 98; 93, call; 93, 94; 93, 95; 94, identifier:isinstance; 95, argument_list; 95, 96; 95, 97; 96, identifier:tagVal; 97, identifier:list; 98, block; 98, 99; 99, expression_statement; 99, 100; 100, call; 100, 101; 100, 104; 101, attribute; 101, 102; 101, 103; 102, identifier:infoVals; 103, identifier:append; 104, argument_list; 104, 105; 105, call; 105, 106; 105, 111; 106, attribute; 106, 107; 106, 110; 107, subscript; 107, 108; 107, 109; 108, identifier:tagVal; 109, integer:0; 110, identifier:replace; 111, argument_list; 111, 112; 111, 113; 112, string:','; 113, string:''; 114, else_clause; 114, 115; 115, block; 115, 116; 116, pass_statement; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 122; 119, subscript; 119, 120; 119, 121; 120, identifier:d; 121, string:'info'; 122, call; 122, 123; 122, 126; 123, attribute; 123, 124; 123, 125; 124, string:', '; 125, identifier:join; 126, argument_list; 126, 127; 127, identifier:infoVals; 128, else_clause; 128, 129; 129, block; 129, 130; 130, for_statement; 130, 131; 130, 132; 130, 133; 131, identifier:tag; 132, identifier:coreValues; 133, block; 133, 134; 133, 144; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:v; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:R; 140, identifier:get; 141, argument_list; 141, 142; 141, 143; 142, identifier:tag; 143, None; 144, if_statement; 144, 145; 144, 150; 144, 165; 145, call; 145, 146; 145, 147; 146, identifier:isinstance; 147, argument_list; 147, 148; 147, 149; 148, identifier:v; 149, identifier:list; 150, block; 150, 151; 151, expression_statement; 151, 152; 152, assignment; 152, 153; 152, 156; 153, subscript; 153, 154; 153, 155; 154, identifier:d; 155, identifier:tag; 156, call; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, string:'|'; 159, identifier:join; 160, argument_list; 160, 161; 161, call; 161, 162; 161, 163; 162, identifier:sorted; 163, argument_list; 163, 164; 164, identifier:v; 165, else_clause; 165, 166; 166, block; 166, 167; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 172; 169, subscript; 169, 170; 169, 171; 170, identifier:d; 171, identifier:tag; 172, identifier:v; 173, expression_statement; 173, 174; 174, assignment; 174, 175; 174, 178; 175, subscript; 175, 176; 175, 177; 176, identifier:d; 177, string:'inCore'; 178, True; 179, if_statement; 179, 180; 179, 181; 180, identifier:addCR; 181, block; 181, 182; 182, expression_statement; 182, 183; 183, assignment; 183, 184; 183, 187; 184, subscript; 184, 185; 184, 186; 185, identifier:d; 186, string:'citations'; 187, call; 187, 188; 187, 191; 188, attribute; 188, 189; 188, 190; 189, string:'|'; 190, identifier:join; 191, argument_list; 191, 192; 192, generator_expression; 192, 193; 192, 197; 193, call; 193, 194; 193, 195; 194, identifier:str; 195, argument_list; 195, 196; 196, identifier:c; 197, for_in_clause; 197, 198; 197, 199; 198, identifier:c; 199, call; 199, 200; 199, 203; 200, attribute; 200, 201; 200, 202; 201, identifier:R; 202, identifier:get; 203, argument_list; 203, 204; 203, 205; 204, string:'citations'; 205, list:[]; 206, else_clause; 206, 207; 207, block; 207, 208; 207, 214; 207, 224; 207, 230; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 213; 210, subscript; 210, 211; 210, 212; 211, identifier:d; 212, string:'MK-ID'; 213, string:'None'; 214, expression_statement; 214, 215; 215, assignment; 215, 216; 215, 219; 216, subscript; 216, 217; 216, 218; 217, identifier:d; 218, string:'info'; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:citation; 222, identifier:allButDOI; 223, argument_list; 224, expression_statement; 224, 225; 225, assignment; 225, 226; 225, 229; 226, subscript; 226, 227; 226, 228; 227, identifier:d; 228, string:'inCore'; 229, False; 230, if_statement; 230, 231; 230, 232; 231, identifier:addCR; 232, block; 232, 233; 233, expression_statement; 233, 234; 234, assignment; 234, 235; 234, 238; 235, subscript; 235, 236; 235, 237; 236, identifier:d; 237, string:'citations'; 238, string:''; 239, else_clause; 239, 240; 240, block; 240, 241; 241, expression_statement; 241, 242; 242, assignment; 242, 243; 242, 246; 243, subscript; 243, 244; 243, 245; 244, identifier:d; 245, string:'info'; 246, call; 246, 247; 246, 250; 247, attribute; 247, 248; 247, 249; 248, identifier:citation; 249, identifier:allButDOI; 250, argument_list; 251, elif_clause; 251, 252; 251, 255; 252, comparison_operator:==; 252, 253; 252, 254; 253, identifier:nodeType; 254, string:'journal'; 255, block; 255, 256; 256, if_statement; 256, 257; 256, 262; 256, 276; 257, call; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, identifier:citation; 260, identifier:isJournal; 261, argument_list; 262, block; 262, 263; 263, expression_statement; 263, 264; 264, assignment; 264, 265; 264, 268; 265, subscript; 265, 266; 265, 267; 266, identifier:d; 267, string:'info'; 268, call; 268, 269; 268, 270; 269, identifier:str; 270, argument_list; 270, 271; 271, call; 271, 272; 271, 275; 272, attribute; 272, 273; 272, 274; 273, identifier:citation; 274, identifier:FullJournalName; 275, argument_list; 276, else_clause; 276, 277; 277, block; 277, 278; 278, expression_statement; 278, 279; 279, assignment; 279, 280; 279, 283; 280, subscript; 280, 281; 280, 282; 281, identifier:d; 282, string:'info'; 283, string:"None"; 284, elif_clause; 284, 285; 284, 288; 285, comparison_operator:==; 285, 286; 285, 287; 286, identifier:nodeType; 287, string:'original'; 288, block; 288, 289; 289, expression_statement; 289, 290; 290, assignment; 290, 291; 290, 294; 291, subscript; 291, 292; 291, 293; 292, identifier:d; 293, string:'info'; 294, call; 294, 295; 294, 296; 295, identifier:str; 296, argument_list; 296, 297; 297, identifier:citation; 298, else_clause; 298, 299; 299, block; 299, 300; 300, expression_statement; 300, 301; 301, assignment; 301, 302; 301, 305; 302, subscript; 302, 303; 302, 304; 303, identifier:d; 304, string:'info'; 305, identifier:idVal; 306, if_statement; 306, 307; 306, 308; 307, identifier:fullInfo; 308, block; 308, 309; 309, expression_statement; 309, 310; 310, assignment; 310, 311; 310, 314; 311, subscript; 311, 312; 311, 313; 312, identifier:d; 313, string:'fullCite'; 314, call; 314, 315; 314, 316; 315, identifier:str; 316, argument_list; 316, 317; 317, identifier:citation; 318, if_statement; 318, 319; 318, 320; 319, identifier:count; 320, block; 320, 321; 321, expression_statement; 321, 322; 322, assignment; 322, 323; 322, 326; 323, subscript; 323, 324; 323, 325; 324, identifier:d; 325, string:'count'; 326, integer:1; 327, return_statement; 327, 328; 328, tuple; 328, 329; 328, 330; 329, identifier:idVal; 330, identifier:d
def makeNodeTuple(citation, idVal, nodeInfo, fullInfo, nodeType, count, coreCitesDict, coreValues, detailedValues, addCR): """Makes a tuple of idVal and a dict of the selected attributes""" d = {} if nodeInfo: if nodeType == 'full': if coreValues: if citation in coreCitesDict: R = coreCitesDict[citation] d['MK-ID'] = R.id if not detailedValues: infoVals = [] for tag in coreValues: tagVal = R.get(tag) if isinstance(tagVal, str): infoVals.append(tagVal.replace(',','')) elif isinstance(tagVal, list): infoVals.append(tagVal[0].replace(',','')) else: pass d['info'] = ', '.join(infoVals) else: for tag in coreValues: v = R.get(tag, None) if isinstance(v, list): d[tag] = '|'.join(sorted(v)) else: d[tag] = v d['inCore'] = True if addCR: d['citations'] = '|'.join((str(c) for c in R.get('citations', []))) else: d['MK-ID'] = 'None' d['info'] = citation.allButDOI() d['inCore'] = False if addCR: d['citations'] = '' else: d['info'] = citation.allButDOI() elif nodeType == 'journal': if citation.isJournal(): d['info'] = str(citation.FullJournalName()) else: d['info'] = "None" elif nodeType == 'original': d['info'] = str(citation) else: d['info'] = idVal if fullInfo: d['fullCite'] = str(citation) if count: d['count'] = 1 return (idVal, d)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:expandRecs; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:G; 5, identifier:RecCollect; 6, identifier:nodeType; 7, identifier:weighted; 8, block; 8, 9; 8, 11; 9, expression_statement; 9, 10; 10, comment; 11, for_statement; 11, 12; 11, 13; 11, 14; 12, identifier:Rec; 13, identifier:RecCollect; 14, block; 14, 15; 14, 34; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:fullCiteList; 18, list_comprehension; 18, 19; 18, 24; 19, call; 19, 20; 19, 21; 20, identifier:makeID; 21, argument_list; 21, 22; 21, 23; 22, identifier:c; 23, identifier:nodeType; 24, for_in_clause; 24, 25; 24, 26; 25, identifier:c; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:Rec; 29, identifier:createCitation; 30, argument_list; 30, 31; 31, keyword_argument; 31, 32; 31, 33; 32, identifier:multiCite; 33, True; 34, if_statement; 34, 35; 34, 41; 35, comparison_operator:>; 35, 36; 35, 40; 36, call; 36, 37; 36, 38; 37, identifier:len; 38, argument_list; 38, 39; 39, identifier:fullCiteList; 40, integer:1; 41, block; 41, 42; 42, for_statement; 42, 43; 42, 46; 42, 50; 43, pattern_list; 43, 44; 43, 45; 44, identifier:i; 45, identifier:citeID1; 46, call; 46, 47; 46, 48; 47, identifier:enumerate; 48, argument_list; 48, 49; 49, identifier:fullCiteList; 50, block; 50, 51; 51, if_statement; 51, 52; 51, 55; 52, comparison_operator:in; 52, 53; 52, 54; 53, identifier:citeID1; 54, identifier:G; 55, block; 55, 56; 56, for_statement; 56, 57; 56, 58; 56, 65; 57, identifier:citeID2; 58, subscript; 58, 59; 58, 60; 59, identifier:fullCiteList; 60, slice; 60, 61; 60, 64; 61, binary_operator:+; 61, 62; 61, 63; 62, identifier:i; 63, integer:1; 64, colon; 65, block; 65, 66; 65, 138; 66, if_statement; 66, 67; 66, 70; 66, 108; 67, comparison_operator:not; 67, 68; 67, 69; 68, identifier:citeID2; 69, identifier:G; 70, block; 70, 71; 70, 84; 71, expression_statement; 71, 72; 72, call; 72, 73; 72, 76; 73, attribute; 73, 74; 73, 75; 74, identifier:G; 75, identifier:add_node; 76, argument_list; 76, 77; 76, 78; 77, identifier:citeID2; 78, dictionary_splat; 78, 79; 79, subscript; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:G; 82, identifier:node; 83, identifier:citeID1; 84, if_statement; 84, 85; 84, 86; 84, 98; 85, identifier:weighted; 86, block; 86, 87; 87, expression_statement; 87, 88; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:G; 91, identifier:add_edge; 92, argument_list; 92, 93; 92, 94; 92, 95; 93, identifier:citeID1; 94, identifier:citeID2; 95, keyword_argument; 95, 96; 95, 97; 96, identifier:weight; 97, integer:1; 98, else_clause; 98, 99; 99, block; 99, 100; 100, expression_statement; 100, 101; 101, call; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:G; 104, identifier:add_edge; 105, argument_list; 105, 106; 105, 107; 106, identifier:citeID1; 107, identifier:citeID2; 108, elif_clause; 108, 109; 108, 110; 109, identifier:weighted; 110, block; 110, 111; 111, try_statement; 111, 112; 111, 124; 112, block; 112, 113; 113, expression_statement; 113, 114; 114, augmented_assignment:+=; 114, 115; 114, 123; 115, subscript; 115, 116; 115, 122; 116, subscript; 116, 117; 116, 120; 116, 121; 117, attribute; 117, 118; 117, 119; 118, identifier:G; 119, identifier:edges; 120, identifier:citeID1; 121, identifier:citeID2; 122, string:'weight'; 123, integer:1; 124, except_clause; 124, 125; 124, 126; 125, identifier:KeyError; 126, block; 126, 127; 127, expression_statement; 127, 128; 128, call; 128, 129; 128, 132; 129, attribute; 129, 130; 129, 131; 130, identifier:G; 131, identifier:add_edge; 132, argument_list; 132, 133; 132, 134; 132, 135; 133, identifier:citeID1; 134, identifier:citeID2; 135, keyword_argument; 135, 136; 135, 137; 136, identifier:weight; 137, integer:1; 138, for_statement; 138, 139; 138, 143; 138, 152; 139, pattern_list; 139, 140; 139, 141; 139, 142; 140, identifier:e1; 141, identifier:e2; 142, identifier:data; 143, call; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:G; 146, identifier:edges; 147, argument_list; 147, 148; 147, 149; 148, identifier:citeID1; 149, keyword_argument; 149, 150; 149, 151; 150, identifier:data; 151, True; 152, block; 152, 153; 153, expression_statement; 153, 154; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:G; 157, identifier:add_edge; 158, argument_list; 158, 159; 158, 160; 158, 161; 159, identifier:citeID2; 160, identifier:e2; 161, dictionary_splat; 161, 162; 162, identifier:data
def expandRecs(G, RecCollect, nodeType, weighted): """Expand all the citations from _RecCollect_""" for Rec in RecCollect: fullCiteList = [makeID(c, nodeType) for c in Rec.createCitation(multiCite = True)] if len(fullCiteList) > 1: for i, citeID1 in enumerate(fullCiteList): if citeID1 in G: for citeID2 in fullCiteList[i + 1:]: if citeID2 not in G: G.add_node(citeID2, **G.node[citeID1]) if weighted: G.add_edge(citeID1, citeID2, weight = 1) else: G.add_edge(citeID1, citeID2) elif weighted: try: G.edges[citeID1, citeID2]['weight'] += 1 except KeyError: G.add_edge(citeID1, citeID2, weight = 1) for e1, e2, data in G.edges(citeID1, data = True): G.add_edge(citeID2, e2, **data)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:writeBib; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:fname; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:maxStringLength; 10, integer:1000; 11, default_parameter; 11, 12; 11, 13; 12, identifier:wosMode; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:reducedOutput; 16, False; 17, default_parameter; 17, 18; 17, 19; 18, identifier:niceIDs; 19, True; 20, block; 20, 21; 20, 23; 20, 62; 20, 69; 20, 70; 20, 126; 21, expression_statement; 21, 22; 22, comment; 23, if_statement; 23, 24; 23, 25; 23, 39; 24, identifier:fname; 25, block; 25, 26; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:f; 29, call; 29, 30; 29, 31; 30, identifier:open; 31, argument_list; 31, 32; 31, 33; 31, 36; 32, identifier:fname; 33, keyword_argument; 33, 34; 33, 35; 34, identifier:mode; 35, string:'w'; 36, keyword_argument; 36, 37; 36, 38; 37, identifier:encoding; 38, string:'utf-8'; 39, else_clause; 39, 40; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:f; 44, call; 44, 45; 44, 46; 45, identifier:open; 46, argument_list; 46, 47; 46, 56; 46, 59; 47, binary_operator:+; 47, 48; 47, 55; 48, subscript; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:self; 51, identifier:name; 52, slice; 52, 53; 52, 54; 53, colon; 54, integer:200; 55, string:'.bib'; 56, keyword_argument; 56, 57; 56, 58; 57, identifier:mode; 58, string:'w'; 59, keyword_argument; 59, 60; 59, 61; 60, identifier:encoding; 61, string:'utf-8'; 62, expression_statement; 62, 63; 63, call; 63, 64; 63, 67; 64, attribute; 64, 65; 64, 66; 65, identifier:f; 66, identifier:write; 67, argument_list; 67, 68; 68, string:"%This file was generated by the metaknowledge Python package.\n%The contents have been automatically generated and are likely to not work with\n%LaTeX without some human intervention. This file is meant for other automatic\n%systems and not to be used directly for making citations\n"; 69, comment; 70, for_statement; 70, 71; 70, 72; 70, 73; 71, identifier:R; 72, identifier:self; 73, block; 73, 74; 74, try_statement; 74, 75; 74, 106; 74, 110; 75, block; 75, 76; 75, 83; 76, expression_statement; 76, 77; 77, call; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:f; 80, identifier:write; 81, argument_list; 81, 82; 82, string:'\n\n'; 83, expression_statement; 83, 84; 84, call; 84, 85; 84, 88; 85, attribute; 85, 86; 85, 87; 86, identifier:f; 87, identifier:write; 88, argument_list; 88, 89; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:R; 92, identifier:bibString; 93, argument_list; 93, 94; 93, 97; 93, 100; 93, 103; 94, keyword_argument; 94, 95; 94, 96; 95, identifier:maxLength; 96, identifier:maxStringLength; 97, keyword_argument; 97, 98; 97, 99; 98, identifier:WOSMode; 99, identifier:wosMode; 100, keyword_argument; 100, 101; 100, 102; 101, identifier:restrictedOutput; 102, identifier:reducedOutput; 103, keyword_argument; 103, 104; 103, 105; 104, identifier:niceID; 105, identifier:niceIDs; 106, except_clause; 106, 107; 106, 108; 107, identifier:BadWOSRecord; 108, block; 108, 109; 109, pass_statement; 110, except_clause; 110, 111; 110, 112; 111, identifier:AttributeError; 112, block; 112, 113; 113, raise_statement; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:RecordsNotCompatible; 116, argument_list; 116, 117; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, string:"The Record '{}', with ID '{}' does not support writing to bibtext files."; 120, identifier:format; 121, argument_list; 121, 122; 121, 123; 122, identifier:R; 123, attribute; 123, 124; 123, 125; 124, identifier:R; 125, identifier:id; 126, expression_statement; 126, 127; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:f; 130, identifier:close; 131, argument_list
def writeBib(self, fname = None, maxStringLength = 1000, wosMode = False, reducedOutput = False, niceIDs = True): """Writes a bibTex entry to _fname_ for each `Record` in the collection. If the Record is of a journal article (PT J) the bibtext type is set to `'article'`, otherwise it is set to `'misc'`. The ID of the entry is the WOS number and all the Record's fields are given as entries with their long names. **Note** This is not meant to be used directly with LaTeX none of the special characters have been escaped and there are a large number of unnecessary fields provided. _niceID_ and _maxLength_ have been provided to make conversions easier only. **Note** Record entries that are lists have their values separated with the string `' and '`, as this is the way bibTex understands # Parameters _fname_ : `optional [str]` > Default `None`, The name of the file to be written. If not given one will be derived from the collection and the file will be written to . _maxStringLength_ : `optional [int]` > Default 1000, The max length for a continuous string. Most bibTex implementation only allow string to be up to 1000 characters ([source](https://www.cs.arizona.edu/~collberg/Teaching/07.231/BibTeX/bibtex.html)), this splits them up into substrings then uses the native string concatenation (the `'#'` character) to allow for longer strings _WOSMode_ : `optional [bool]` > Default `False`, if `True` the data produced will be unprocessed and use double curly braces. This is the style WOS produces bib files in and mostly macthes that. _restrictedOutput_ : `optional [bool]` > Default `False`, if `True` the tags output will be limited to: `'AF'`, `'BF'`, `'ED'`, `'TI'`, `'SO'`, `'LA'`, `'NR'`, `'TC'`, `'Z9'`, `'PU'`, `'J9'`, `'PY'`, `'PD'`, `'VL'`, `'IS'`, `'SU'`, `'PG'`, `'DI'`, `'D2'`, and `'UT'` _niceID_ : `optional [bool]` > Default `True`, if `True` the IDs used will be derived from the authors, publishing date and title, if `False` it will be the UT tag """ if fname: f = open(fname, mode = 'w', encoding = 'utf-8') else: f = open(self.name[:200] + '.bib', mode = 'w', encoding = 'utf-8') f.write("%This file was generated by the metaknowledge Python package.\n%The contents have been automatically generated and are likely to not work with\n%LaTeX without some human intervention. This file is meant for other automatic\n%systems and not to be used directly for making citations\n") #I figure this is worth mentioning, as someone will get annoyed at none of the special characters being escaped and how terrible some of the fields look to humans for R in self: try: f.write('\n\n') f.write(R.bibString(maxLength = maxStringLength, WOSMode = wosMode, restrictedOutput = reducedOutput, niceID = niceIDs)) except BadWOSRecord: pass except AttributeError: raise RecordsNotCompatible("The Record '{}', with ID '{}' does not support writing to bibtext files.".format(R, R.id)) f.close()
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:makeDict; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:onlyTheseTags; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:longNames; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:raw; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:numAuthors; 16, True; 17, default_parameter; 17, 18; 17, 19; 18, identifier:genderCounts; 19, True; 20, block; 20, 21; 20, 23; 20, 87; 20, 110; 20, 120; 20, 129; 20, 148; 20, 244; 21, expression_statement; 21, 22; 22, comment; 23, if_statement; 23, 24; 23, 25; 23, 57; 24, identifier:onlyTheseTags; 25, block; 25, 26; 25, 53; 26, for_statement; 26, 27; 26, 28; 26, 35; 27, identifier:i; 28, call; 28, 29; 28, 30; 29, identifier:range; 30, argument_list; 30, 31; 31, call; 31, 32; 31, 33; 32, identifier:len; 33, argument_list; 33, 34; 34, identifier:onlyTheseTags; 35, block; 35, 36; 36, if_statement; 36, 37; 36, 42; 37, comparison_operator:in; 37, 38; 37, 41; 38, subscript; 38, 39; 38, 40; 39, identifier:onlyTheseTags; 40, identifier:i; 41, identifier:fullToTagDict; 42, block; 42, 43; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 48; 45, subscript; 45, 46; 45, 47; 46, identifier:onlyTheseTags; 47, identifier:i; 48, subscript; 48, 49; 48, 50; 49, identifier:fullToTagDict; 50, subscript; 50, 51; 50, 52; 51, identifier:onlyTheseTags; 52, identifier:i; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:retrievedFields; 56, identifier:onlyTheseTags; 57, else_clause; 57, 58; 58, block; 58, 59; 58, 63; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:retrievedFields; 62, list:[]; 63, for_statement; 63, 64; 63, 65; 63, 66; 64, identifier:R; 65, identifier:self; 66, block; 66, 67; 66, 83; 67, expression_statement; 67, 68; 68, assignment; 68, 69; 68, 70; 69, identifier:tagsLst; 70, list_comprehension; 70, 71; 70, 72; 70, 79; 71, identifier:t; 72, for_in_clause; 72, 73; 72, 74; 73, identifier:t; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:R; 77, identifier:keys; 78, argument_list; 79, if_clause; 79, 80; 80, comparison_operator:not; 80, 81; 80, 82; 81, identifier:t; 82, identifier:retrievedFields; 83, expression_statement; 83, 84; 84, augmented_assignment:+=; 84, 85; 84, 86; 85, identifier:retrievedFields; 86, identifier:tagsLst; 87, if_statement; 87, 88; 87, 89; 88, identifier:longNames; 89, block; 89, 90; 90, try_statement; 90, 91; 90, 102; 91, block; 91, 92; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:retrievedFields; 95, list_comprehension; 95, 96; 95, 99; 96, subscript; 96, 97; 96, 98; 97, identifier:tagToFullDict; 98, identifier:t; 99, for_in_clause; 99, 100; 99, 101; 100, identifier:t; 101, identifier:retrievedFields; 102, except_clause; 102, 103; 102, 104; 103, identifier:KeyError; 104, block; 104, 105; 105, raise_statement; 105, 106; 106, call; 106, 107; 106, 108; 107, identifier:KeyError; 108, argument_list; 108, 109; 109, string:"One of the tags could not be converted to a long name."; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:retDict; 113, dictionary_comprehension; 113, 114; 113, 117; 114, pair; 114, 115; 114, 116; 115, identifier:k; 116, list:[]; 117, for_in_clause; 117, 118; 117, 119; 118, identifier:k; 119, identifier:retrievedFields; 120, if_statement; 120, 121; 120, 122; 121, identifier:numAuthors; 122, block; 122, 123; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 128; 125, subscript; 125, 126; 125, 127; 126, identifier:retDict; 127, string:"num-Authors"; 128, list:[]; 129, if_statement; 129, 130; 129, 131; 130, identifier:genderCounts; 131, block; 131, 132; 132, expression_statement; 132, 133; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:retDict; 136, identifier:update; 137, argument_list; 137, 138; 138, dictionary; 138, 139; 138, 142; 138, 145; 139, pair; 139, 140; 139, 141; 140, string:'num-Male'; 141, list:[]; 142, pair; 142, 143; 142, 144; 143, string:'num-Female'; 144, list:[]; 145, pair; 145, 146; 145, 147; 146, string:'num-Unknown'; 147, list:[]; 148, for_statement; 148, 149; 148, 150; 148, 151; 149, identifier:R; 150, identifier:self; 151, block; 151, 152; 151, 173; 151, 217; 152, if_statement; 152, 153; 152, 154; 153, identifier:numAuthors; 154, block; 154, 155; 155, expression_statement; 155, 156; 156, call; 156, 157; 156, 162; 157, attribute; 157, 158; 157, 161; 158, subscript; 158, 159; 158, 160; 159, identifier:retDict; 160, string:"num-Authors"; 161, identifier:append; 162, argument_list; 162, 163; 163, call; 163, 164; 163, 165; 164, identifier:len; 165, argument_list; 165, 166; 166, call; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:R; 169, identifier:get; 170, argument_list; 170, 171; 170, 172; 171, string:'authorsShort'; 172, list:[]; 173, if_statement; 173, 174; 173, 175; 174, identifier:genderCounts; 175, block; 175, 176; 175, 190; 175, 199; 175, 208; 176, expression_statement; 176, 177; 177, assignment; 177, 178; 177, 182; 178, pattern_list; 178, 179; 178, 180; 178, 181; 179, identifier:m; 180, identifier:f; 181, identifier:u; 182, call; 182, 183; 182, 186; 183, attribute; 183, 184; 183, 185; 184, identifier:R; 185, identifier:authGenders; 186, argument_list; 186, 187; 187, keyword_argument; 187, 188; 187, 189; 188, identifier:_countsTuple; 189, True; 190, expression_statement; 190, 191; 191, call; 191, 192; 191, 197; 192, attribute; 192, 193; 192, 196; 193, subscript; 193, 194; 193, 195; 194, identifier:retDict; 195, string:'num-Male'; 196, identifier:append; 197, argument_list; 197, 198; 198, identifier:m; 199, expression_statement; 199, 200; 200, call; 200, 201; 200, 206; 201, attribute; 201, 202; 201, 205; 202, subscript; 202, 203; 202, 204; 203, identifier:retDict; 204, string:'num-Female'; 205, identifier:append; 206, argument_list; 206, 207; 207, identifier:f; 208, expression_statement; 208, 209; 209, call; 209, 210; 209, 215; 210, attribute; 210, 211; 210, 214; 211, subscript; 211, 212; 211, 213; 212, identifier:retDict; 213, string:'num-Unknown'; 214, identifier:append; 215, argument_list; 215, 216; 216, identifier:u; 217, for_statement; 217, 218; 217, 221; 217, 234; 218, pattern_list; 218, 219; 218, 220; 219, identifier:k; 220, identifier:v; 221, call; 221, 222; 221, 233; 222, attribute; 222, 223; 222, 232; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:R; 226, identifier:subDict; 227, argument_list; 227, 228; 227, 229; 228, identifier:retrievedFields; 229, keyword_argument; 229, 230; 229, 231; 230, identifier:raw; 231, identifier:raw; 232, identifier:items; 233, argument_list; 234, block; 234, 235; 235, expression_statement; 235, 236; 236, call; 236, 237; 236, 242; 237, attribute; 237, 238; 237, 241; 238, subscript; 238, 239; 238, 240; 239, identifier:retDict; 240, identifier:k; 241, identifier:append; 242, argument_list; 242, 243; 243, identifier:v; 244, return_statement; 244, 245; 245, identifier:retDict
def makeDict(self, onlyTheseTags = None, longNames = False, raw = False, numAuthors = True, genderCounts = True): """Returns a dict with each key a tag and the values being lists of the values for each of the Records in the collection, `None` is given when there is no value and they are in the same order across each tag. When used with pandas: `pandas.DataFrame(RC.makeDict())` returns a data frame with each column a tag and each row a Record. # Parameters _onlyTheseTags_ : `optional [iterable]` > Default `None`, if an iterable (list, tuple, etc) only the tags in _onlyTheseTags_ will be used, if not given then all tags in the records are given. > If you want to use all known tags pass [metaknowledge.knownTagsList](./ExtendedRecord.html#metaknowledge.ExtendedRecord.tagProcessingFunc). _longNames_ : `optional [bool]` > Default `False`, if `True` will convert the tags to their longer names, otherwise the short 2 character ones will be used. _cleanedVal_ : `optional [bool]` > Default `True`, if `True` the processed values for each `Record`'s field will be provided, otherwise the raw values are given. _numAuthors_ : `optional [bool]` > Default `True`, if `True` adds the number of authors as the column `'numAuthors'`. """ if onlyTheseTags: for i in range(len(onlyTheseTags)): if onlyTheseTags[i] in fullToTagDict: onlyTheseTags[i] = fullToTagDict[onlyTheseTags[i]] retrievedFields = onlyTheseTags else: retrievedFields = [] for R in self: tagsLst = [t for t in R.keys() if t not in retrievedFields] retrievedFields += tagsLst if longNames: try: retrievedFields = [tagToFullDict[t] for t in retrievedFields] except KeyError: raise KeyError("One of the tags could not be converted to a long name.") retDict = {k : [] for k in retrievedFields} if numAuthors: retDict["num-Authors"] = [] if genderCounts: retDict.update({'num-Male' : [], 'num-Female' : [], 'num-Unknown' : []}) for R in self: if numAuthors: retDict["num-Authors"].append(len(R.get('authorsShort', []))) if genderCounts: m, f, u = R.authGenders(_countsTuple = True) retDict['num-Male'].append(m) retDict['num-Female'].append(f) retDict['num-Unknown'].append(u) for k, v in R.subDict(retrievedFields, raw = raw).items(): retDict[k].append(v) return retDict
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 44; 2, function_name:networkCoCitation; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 3, 23; 3, 26; 3, 29; 3, 32; 3, 35; 3, 38; 3, 41; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:dropAnon; 7, True; 8, default_parameter; 8, 9; 8, 10; 9, identifier:nodeType; 10, string:"full"; 11, default_parameter; 11, 12; 11, 13; 12, identifier:nodeInfo; 13, True; 14, default_parameter; 14, 15; 14, 16; 15, identifier:fullInfo; 16, False; 17, default_parameter; 17, 18; 17, 19; 18, identifier:weighted; 19, True; 20, default_parameter; 20, 21; 20, 22; 21, identifier:dropNonJournals; 22, False; 23, default_parameter; 23, 24; 23, 25; 24, identifier:count; 25, True; 26, default_parameter; 26, 27; 26, 28; 27, identifier:keyWords; 28, None; 29, default_parameter; 29, 30; 29, 31; 30, identifier:detailedCore; 31, True; 32, default_parameter; 32, 33; 32, 34; 33, identifier:detailedCoreAttributes; 34, False; 35, default_parameter; 35, 36; 35, 37; 36, identifier:coreOnly; 37, False; 38, default_parameter; 38, 39; 38, 40; 39, identifier:expandedCore; 40, False; 41, default_parameter; 41, 42; 41, 43; 42, identifier:addCR; 43, False; 44, block; 44, 45; 44, 47; 44, 56; 44, 71; 44, 75; 44, 111; 44, 119; 44, 123; 44, 129; 44, 150; 44, 320; 45, expression_statement; 45, 46; 46, comment; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:allowedTypes; 50, list:["full", "original", "author", "journal", "year"]; 50, 51; 50, 52; 50, 53; 50, 54; 50, 55; 51, string:"full"; 52, string:"original"; 53, string:"author"; 54, string:"journal"; 55, string:"year"; 56, if_statement; 56, 57; 56, 60; 57, comparison_operator:not; 57, 58; 57, 59; 58, identifier:nodeType; 59, identifier:allowedTypes; 60, block; 60, 61; 61, raise_statement; 61, 62; 62, call; 62, 63; 62, 64; 63, identifier:RCValueError; 64, argument_list; 64, 65; 65, call; 65, 66; 65, 69; 66, attribute; 66, 67; 66, 68; 67, string:"{} is not an allowed nodeType."; 68, identifier:format; 69, argument_list; 69, 70; 70, identifier:nodeType; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:coreValues; 74, list:[]; 75, if_statement; 75, 76; 75, 80; 76, call; 76, 77; 76, 78; 77, identifier:bool; 78, argument_list; 78, 79; 79, identifier:detailedCore; 80, block; 80, 81; 81, try_statement; 81, 82; 81, 97; 82, block; 82, 83; 83, for_statement; 83, 84; 83, 85; 83, 86; 84, identifier:tag; 85, identifier:detailedCore; 86, block; 86, 87; 87, expression_statement; 87, 88; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:coreValues; 91, identifier:append; 92, argument_list; 92, 93; 93, call; 93, 94; 93, 95; 94, identifier:normalizeToTag; 95, argument_list; 95, 96; 96, identifier:tag; 97, except_clause; 97, 98; 97, 99; 98, identifier:TypeError; 99, block; 99, 100; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 103; 102, identifier:coreValues; 103, list:['id', 'authorsFull', 'year', 'title', 'journal', 'volume', 'beginningPage']; 103, 104; 103, 105; 103, 106; 103, 107; 103, 108; 103, 109; 103, 110; 104, string:'id'; 105, string:'authorsFull'; 106, string:'year'; 107, string:'title'; 108, string:'journal'; 109, string:'volume'; 110, string:'beginningPage'; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:tmpgrph; 114, call; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:nx; 117, identifier:Graph; 118, argument_list; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:pcount; 122, integer:0; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 126; 125, identifier:progArgs; 126, tuple; 126, 127; 126, 128; 127, integer:0; 128, string:"Starting to make a co-citation network"; 129, if_statement; 129, 130; 129, 133; 129, 141; 130, attribute; 130, 131; 130, 132; 131, identifier:metaknowledge; 132, identifier:VERBOSE_MODE; 133, block; 133, 134; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:progKwargs; 137, dictionary; 137, 138; 138, pair; 138, 139; 138, 140; 139, string:'dummy'; 140, False; 141, else_clause; 141, 142; 142, block; 142, 143; 143, expression_statement; 143, 144; 144, assignment; 144, 145; 144, 146; 145, identifier:progKwargs; 146, dictionary; 146, 147; 147, pair; 147, 148; 147, 149; 148, string:'dummy'; 149, True; 150, with_statement; 150, 151; 150, 163; 151, with_clause; 151, 152; 152, with_item; 152, 153; 153, as_pattern; 153, 154; 153, 161; 154, call; 154, 155; 154, 156; 155, identifier:_ProgressBar; 156, argument_list; 156, 157; 156, 159; 157, list_splat; 157, 158; 158, identifier:progArgs; 159, dictionary_splat; 159, 160; 160, identifier:progKwargs; 161, as_pattern_target; 161, 162; 162, identifier:PBar; 163, block; 163, 164; 163, 212; 163, 283; 163, 305; 164, if_statement; 164, 165; 164, 170; 164, 202; 165, boolean_operator:or; 165, 166; 165, 169; 166, boolean_operator:or; 166, 167; 166, 168; 167, identifier:coreOnly; 168, identifier:coreValues; 169, identifier:expandedCore; 170, block; 170, 171; 170, 185; 171, expression_statement; 171, 172; 172, assignment; 172, 173; 172, 174; 173, identifier:coreCitesDict; 174, dictionary_comprehension; 174, 175; 174, 182; 175, pair; 175, 176; 175, 181; 176, call; 176, 177; 176, 180; 177, attribute; 177, 178; 177, 179; 178, identifier:R; 179, identifier:createCitation; 180, argument_list; 181, identifier:R; 182, for_in_clause; 182, 183; 182, 184; 183, identifier:R; 184, identifier:self; 185, if_statement; 185, 186; 185, 187; 185, 196; 186, identifier:coreOnly; 187, block; 187, 188; 188, expression_statement; 188, 189; 189, assignment; 189, 190; 189, 191; 190, identifier:coreCites; 191, call; 191, 192; 191, 195; 192, attribute; 192, 193; 192, 194; 193, identifier:coreCitesDict; 194, identifier:keys; 195, argument_list; 196, else_clause; 196, 197; 197, block; 197, 198; 198, expression_statement; 198, 199; 199, assignment; 199, 200; 199, 201; 200, identifier:coreCites; 201, None; 202, else_clause; 202, 203; 203, block; 203, 204; 203, 208; 204, expression_statement; 204, 205; 205, assignment; 205, 206; 205, 207; 206, identifier:coreCitesDict; 207, None; 208, expression_statement; 208, 209; 209, assignment; 209, 210; 209, 211; 210, identifier:coreCites; 211, None; 212, for_statement; 212, 213; 212, 214; 212, 215; 213, identifier:R; 214, identifier:self; 215, block; 215, 216; 215, 241; 215, 250; 216, if_statement; 216, 217; 216, 218; 217, identifier:PBar; 218, block; 218, 219; 218, 223; 219, expression_statement; 219, 220; 220, augmented_assignment:+=; 220, 221; 220, 222; 221, identifier:pcount; 222, integer:1; 223, expression_statement; 223, 224; 224, call; 224, 225; 224, 228; 225, attribute; 225, 226; 225, 227; 226, identifier:PBar; 227, identifier:updateVal; 228, argument_list; 228, 229; 228, 235; 229, binary_operator:/; 229, 230; 229, 231; 230, identifier:pcount; 231, call; 231, 232; 231, 233; 232, identifier:len; 233, argument_list; 233, 234; 234, identifier:self; 235, call; 235, 236; 235, 239; 236, attribute; 236, 237; 236, 238; 237, string:"Analyzing: {}"; 238, identifier:format; 239, argument_list; 239, 240; 240, identifier:R; 241, expression_statement; 241, 242; 242, assignment; 242, 243; 242, 244; 243, identifier:Cites; 244, call; 244, 245; 244, 248; 245, attribute; 245, 246; 245, 247; 246, identifier:R; 247, identifier:get; 248, argument_list; 248, 249; 249, string:'citations'; 250, if_statement; 250, 251; 250, 252; 251, identifier:Cites; 252, block; 252, 253; 252, 265; 253, expression_statement; 253, 254; 254, assignment; 254, 255; 254, 256; 255, identifier:filteredCites; 256, call; 256, 257; 256, 258; 257, identifier:filterCites; 258, argument_list; 258, 259; 258, 260; 258, 261; 258, 262; 258, 263; 258, 264; 259, identifier:Cites; 260, identifier:nodeType; 261, identifier:dropAnon; 262, identifier:dropNonJournals; 263, identifier:keyWords; 264, identifier:coreCites; 265, expression_statement; 265, 266; 266, call; 266, 267; 266, 268; 267, identifier:addToNetwork; 268, argument_list; 268, 269; 268, 270; 268, 271; 268, 272; 268, 273; 268, 274; 268, 275; 268, 276; 268, 277; 268, 278; 268, 279; 268, 280; 269, identifier:tmpgrph; 270, identifier:filteredCites; 271, identifier:count; 272, identifier:weighted; 273, identifier:nodeType; 274, identifier:nodeInfo; 275, identifier:fullInfo; 276, identifier:coreCitesDict; 277, identifier:coreValues; 278, identifier:detailedCoreAttributes; 279, identifier:addCR; 280, keyword_argument; 280, 281; 280, 282; 281, identifier:headNd; 282, None; 283, if_statement; 283, 284; 283, 285; 284, identifier:expandedCore; 285, block; 285, 286; 285, 297; 286, if_statement; 286, 287; 286, 288; 287, identifier:PBar; 288, block; 288, 289; 289, expression_statement; 289, 290; 290, call; 290, 291; 290, 294; 291, attribute; 291, 292; 291, 293; 292, identifier:PBar; 293, identifier:updateVal; 294, argument_list; 294, 295; 294, 296; 295, float:.98; 296, string:"Expanding core Records"; 297, expression_statement; 297, 298; 298, call; 298, 299; 298, 300; 299, identifier:expandRecs; 300, argument_list; 300, 301; 300, 302; 300, 303; 300, 304; 301, identifier:tmpgrph; 302, identifier:self; 303, identifier:nodeType; 304, identifier:weighted; 305, if_statement; 305, 306; 305, 307; 306, identifier:PBar; 307, block; 307, 308; 308, expression_statement; 308, 309; 309, call; 309, 310; 309, 313; 310, attribute; 310, 311; 310, 312; 311, identifier:PBar; 312, identifier:finish; 313, argument_list; 313, 314; 314, call; 314, 315; 314, 318; 315, attribute; 315, 316; 315, 317; 316, string:"Done making a co-citation network from {}"; 317, identifier:format; 318, argument_list; 318, 319; 319, identifier:self; 320, return_statement; 320, 321; 321, identifier:tmpgrph
def networkCoCitation(self, dropAnon = True, nodeType = "full", nodeInfo = True, fullInfo = False, weighted = True, dropNonJournals = False, count = True, keyWords = None, detailedCore = True, detailedCoreAttributes = False, coreOnly = False, expandedCore = False, addCR = False): """Creates a co-citation network for the RecordCollection. # Parameters _nodeType_ : `optional [str]` > One of `"full"`, `"original"`, `"author"`, `"journal"` or `"year"`. Specifies the value of the nodes in the graph. The default `"full"` causes the citations to be compared holistically using the [metaknowledge.Citation](./Citation.html#metaknowledge.citation.Citation) builtin comparison operators. `"original"` uses the raw original strings of the citations. While `"author"`, `"journal"` and `"year"` each use the author, journal and year respectively. _dropAnon_ : `optional [bool]` > default `True`, if `True` citations labeled anonymous are removed from the network _nodeInfo_ : `optional [bool]` > default `True`, if `True` an extra piece of information is stored with each node. The extra inforamtion is detemined by _nodeType_. _fullInfo_ : `optional [bool]` > default `False`, if `True` the original citation string is added to the node as an extra value, the attribute is labeled as fullCite _weighted_ : `optional [bool]` > default `True`, wether the edges are weighted. If `True` the edges are weighted by the number of citations. _dropNonJournals_ : `optional [bool]` > default `False`, wether to drop citations of non-journals _count_ : `optional [bool]` > default `True`, causes the number of occurrences of a node to be counted _keyWords_ : `optional [str] or [list[str]]` > A string or list of strings that the citations are checked against, if they contain any of the strings they are removed from the network _detailedCore_ : `optional [bool or iterable[WOS tag Strings]]` > default `True`, if `True` all Citations from the core (those of records in the RecordCollection) and the _nodeType_ is `'full'` all nodes from the core will be given info strings composed of information from the Record objects themselves. This is Equivalent to passing the list: `['AF', 'PY', 'TI', 'SO', 'VL', 'BP']`. > If _detailedCore_ is an iterable (That evaluates to `True`) of WOS Tags (or long names) The values of those tags will be used to make the info attribute. All > The resultant string is the values of each tag, with commas removed, seperated by `', '`, just like the info given by non-core Citations. Note that for tags like `'AF'` that return lists only the first entry in the list will be used. Also a second attribute is created for all nodes called inCore wich is a boolean describing if the node is in the core or not. > Note: _detailedCore_ is not identical to the _detailedInfo_ argument of [Recordcollection.networkCoAuthor()](#metaknowledge.RecordCollection.networkCoAuthor) _coreOnly_ : `optional [bool]` > default `False`, if `True` only Citations from the RecordCollection will be included in the network _expandedCore_ : `optional [bool]` > default `False`, if `True` all citations in the ouput graph that are records in the collection will be duplicated for each author. If the nodes are `"full"`, `"original"` or `"author"` this will result in new noded being created for the other options the results are **not** defined or tested. Edges will be created between each of the nodes for each record expanded, attributes will be copied from exiting nodes. # Returns `Networkx Graph` > A networkx graph with hashes as ID and co-citation as edges """ allowedTypes = ["full", "original", "author", "journal", "year"] if nodeType not in allowedTypes: raise RCValueError("{} is not an allowed nodeType.".format(nodeType)) coreValues = [] if bool(detailedCore): try: for tag in detailedCore: coreValues.append(normalizeToTag(tag)) except TypeError: coreValues = ['id', 'authorsFull', 'year', 'title', 'journal', 'volume', 'beginningPage'] tmpgrph = nx.Graph() pcount = 0 progArgs = (0, "Starting to make a co-citation network") if metaknowledge.VERBOSE_MODE: progKwargs = {'dummy' : False} else: progKwargs = {'dummy' : True} with _ProgressBar(*progArgs, **progKwargs) as PBar: if coreOnly or coreValues or expandedCore: coreCitesDict = {R.createCitation() : R for R in self} if coreOnly: coreCites = coreCitesDict.keys() else: coreCites = None else: coreCitesDict = None coreCites = None for R in self: if PBar: pcount += 1 PBar.updateVal(pcount / len(self), "Analyzing: {}".format(R)) Cites = R.get('citations') if Cites: filteredCites = filterCites(Cites, nodeType, dropAnon, dropNonJournals, keyWords, coreCites) addToNetwork(tmpgrph, filteredCites, count, weighted, nodeType, nodeInfo , fullInfo, coreCitesDict, coreValues, detailedCoreAttributes, addCR, headNd = None) if expandedCore: if PBar: PBar.updateVal(.98, "Expanding core Records") expandRecs(tmpgrph, self, nodeType, weighted) if PBar: PBar.finish("Done making a co-citation network from {}".format(self)) return tmpgrph
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:networkBibCoupling; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:weighted; 7, True; 8, default_parameter; 8, 9; 8, 10; 9, identifier:fullInfo; 10, False; 11, default_parameter; 11, 12; 11, 13; 12, identifier:addCR; 13, False; 14, block; 14, 15; 14, 17; 14, 23; 14, 44; 14, 327; 15, expression_statement; 15, 16; 16, comment; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:progArgs; 20, tuple; 20, 21; 20, 22; 21, integer:0; 22, string:"Make a citation network for coupling"; 23, if_statement; 23, 24; 23, 27; 23, 35; 24, attribute; 24, 25; 24, 26; 25, identifier:metaknowledge; 26, identifier:VERBOSE_MODE; 27, block; 27, 28; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:progKwargs; 31, dictionary; 31, 32; 32, pair; 32, 33; 32, 34; 33, string:'dummy'; 34, False; 35, else_clause; 35, 36; 36, block; 36, 37; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:progKwargs; 40, dictionary; 40, 41; 41, pair; 41, 42; 41, 43; 42, string:'dummy'; 43, True; 44, with_statement; 44, 45; 44, 57; 45, with_clause; 45, 46; 46, with_item; 46, 47; 47, as_pattern; 47, 48; 47, 55; 48, call; 48, 49; 48, 50; 49, identifier:_ProgressBar; 50, argument_list; 50, 51; 50, 53; 51, list_splat; 51, 52; 52, identifier:progArgs; 53, dictionary_splat; 53, 54; 54, identifier:progKwargs; 55, as_pattern_target; 55, 56; 56, identifier:PBar; 57, block; 57, 58; 57, 90; 57, 94; 57, 101; 57, 109; 57, 117; 57, 123; 57, 191; 57, 195; 57, 202; 57, 315; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:citeGrph; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:self; 64, identifier:networkCitation; 65, argument_list; 65, 66; 65, 69; 65, 72; 65, 75; 65, 78; 65, 81; 65, 84; 65, 87; 66, keyword_argument; 66, 67; 66, 68; 67, identifier:weighted; 68, False; 69, keyword_argument; 69, 70; 69, 71; 70, identifier:directed; 71, True; 72, keyword_argument; 72, 73; 72, 74; 73, identifier:detailedCore; 74, True; 75, keyword_argument; 75, 76; 75, 77; 76, identifier:fullInfo; 77, identifier:fullInfo; 78, keyword_argument; 78, 79; 78, 80; 79, identifier:count; 80, False; 81, keyword_argument; 81, 82; 81, 83; 82, identifier:nodeInfo; 83, True; 84, keyword_argument; 84, 85; 84, 86; 85, identifier:addCR; 86, identifier:addCR; 87, keyword_argument; 87, 88; 87, 89; 88, identifier:_quiet; 89, True; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:pcount; 93, integer:0; 94, expression_statement; 94, 95; 95, assignment; 95, 96; 95, 97; 96, identifier:pmax; 97, call; 97, 98; 97, 99; 98, identifier:len; 99, argument_list; 99, 100; 100, identifier:citeGrph; 101, expression_statement; 101, 102; 102, call; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:PBar; 105, identifier:updateVal; 106, argument_list; 106, 107; 106, 108; 107, float:.2; 108, string:"Starting to classify nodes"; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:workingGrph; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:nx; 115, identifier:Graph; 116, argument_list; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:couplingSet; 120, call; 120, 121; 120, 122; 121, identifier:set; 122, argument_list; 123, for_statement; 123, 124; 123, 127; 123, 135; 124, pattern_list; 124, 125; 124, 126; 125, identifier:n; 126, identifier:d; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:citeGrph; 130, identifier:nodes; 131, argument_list; 131, 132; 132, keyword_argument; 132, 133; 132, 134; 133, identifier:data; 134, True; 135, block; 135, 136; 135, 140; 135, 160; 135, 174; 136, expression_statement; 136, 137; 137, augmented_assignment:+=; 137, 138; 137, 139; 138, identifier:pcount; 139, integer:1; 140, expression_statement; 140, 141; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:PBar; 144, identifier:updateVal; 145, argument_list; 145, 146; 145, 154; 146, binary_operator:+; 146, 147; 146, 148; 147, float:.2; 148, binary_operator:*; 148, 149; 148, 150; 149, float:.4; 150, parenthesized_expression; 150, 151; 151, binary_operator:/; 151, 152; 151, 153; 152, identifier:pcount; 153, identifier:pmax; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, string:"Classifying: {}"; 157, identifier:format; 158, argument_list; 158, 159; 159, identifier:n; 160, if_statement; 160, 161; 160, 164; 161, subscript; 161, 162; 161, 163; 162, identifier:d; 163, string:'inCore'; 164, block; 164, 165; 165, expression_statement; 165, 166; 166, call; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:workingGrph; 169, identifier:add_node; 170, argument_list; 170, 171; 170, 172; 171, identifier:n; 172, dictionary_splat; 172, 173; 173, identifier:d; 174, if_statement; 174, 175; 174, 183; 175, comparison_operator:>; 175, 176; 175, 182; 176, call; 176, 177; 176, 180; 177, attribute; 177, 178; 177, 179; 178, identifier:citeGrph; 179, identifier:in_degree; 180, argument_list; 180, 181; 181, identifier:n; 182, integer:0; 183, block; 183, 184; 184, expression_statement; 184, 185; 185, call; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:couplingSet; 188, identifier:add; 189, argument_list; 189, 190; 190, identifier:n; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:pcount; 194, integer:0; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:pmax; 198, call; 198, 199; 198, 200; 199, identifier:len; 200, argument_list; 200, 201; 201, identifier:couplingSet; 202, for_statement; 202, 203; 202, 204; 202, 205; 203, identifier:n; 204, identifier:couplingSet; 205, block; 205, 206; 205, 226; 205, 238; 206, expression_statement; 206, 207; 207, call; 207, 208; 207, 211; 208, attribute; 208, 209; 208, 210; 209, identifier:PBar; 210, identifier:updateVal; 211, argument_list; 211, 212; 211, 220; 212, binary_operator:+; 212, 213; 212, 214; 213, float:.6; 214, binary_operator:*; 214, 215; 214, 216; 215, float:.4; 216, parenthesized_expression; 216, 217; 217, binary_operator:/; 217, 218; 217, 219; 218, identifier:pcount; 219, identifier:pmax; 220, call; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, string:"Coupling: {}"; 223, identifier:format; 224, argument_list; 224, 225; 225, identifier:n; 226, expression_statement; 226, 227; 227, assignment; 227, 228; 227, 229; 228, identifier:citesLst; 229, call; 229, 230; 229, 231; 230, identifier:list; 231, argument_list; 231, 232; 232, call; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:citeGrph; 235, identifier:in_edges; 236, argument_list; 236, 237; 237, identifier:n; 238, for_statement; 238, 239; 238, 242; 238, 246; 239, pattern_list; 239, 240; 239, 241; 240, identifier:i; 241, identifier:edgeOuter; 242, call; 242, 243; 242, 244; 243, identifier:enumerate; 244, argument_list; 244, 245; 245, identifier:citesLst; 246, block; 246, 247; 246, 253; 247, expression_statement; 247, 248; 248, assignment; 248, 249; 248, 250; 249, identifier:outerNode; 250, subscript; 250, 251; 250, 252; 251, identifier:edgeOuter; 252, integer:0; 253, for_statement; 253, 254; 253, 255; 253, 262; 254, identifier:edgeInner; 255, subscript; 255, 256; 255, 257; 256, identifier:citesLst; 257, slice; 257, 258; 257, 261; 258, binary_operator:+; 258, 259; 258, 260; 259, identifier:i; 260, integer:1; 261, colon; 262, block; 262, 263; 262, 269; 263, expression_statement; 263, 264; 264, assignment; 264, 265; 264, 266; 265, identifier:innerNode; 266, subscript; 266, 267; 266, 268; 267, identifier:edgeInner; 268, integer:0; 269, if_statement; 269, 270; 269, 279; 269, 291; 269, 305; 270, boolean_operator:and; 270, 271; 270, 272; 271, identifier:weighted; 272, call; 272, 273; 272, 276; 273, attribute; 273, 274; 273, 275; 274, identifier:workingGrph; 275, identifier:has_edge; 276, argument_list; 276, 277; 276, 278; 277, identifier:outerNode; 278, identifier:innerNode; 279, block; 279, 280; 280, expression_statement; 280, 281; 281, augmented_assignment:+=; 281, 282; 281, 290; 282, subscript; 282, 283; 282, 289; 283, subscript; 283, 284; 283, 287; 283, 288; 284, attribute; 284, 285; 284, 286; 285, identifier:workingGrph; 286, identifier:edges; 287, identifier:outerNode; 288, identifier:innerNode; 289, string:'weight'; 290, integer:1; 291, elif_clause; 291, 292; 291, 293; 292, identifier:weighted; 293, block; 293, 294; 294, expression_statement; 294, 295; 295, call; 295, 296; 295, 299; 296, attribute; 296, 297; 296, 298; 297, identifier:workingGrph; 298, identifier:add_edge; 299, argument_list; 299, 300; 299, 301; 299, 302; 300, identifier:outerNode; 301, identifier:innerNode; 302, keyword_argument; 302, 303; 302, 304; 303, identifier:weight; 304, integer:1; 305, else_clause; 305, 306; 306, block; 306, 307; 307, expression_statement; 307, 308; 308, call; 308, 309; 308, 312; 309, attribute; 309, 310; 309, 311; 310, identifier:workingGrph; 311, identifier:add_edge; 312, argument_list; 312, 313; 312, 314; 313, identifier:outerNode; 314, identifier:innerNode; 315, expression_statement; 315, 316; 316, call; 316, 317; 316, 320; 317, attribute; 317, 318; 317, 319; 318, identifier:PBar; 319, identifier:finish; 320, argument_list; 320, 321; 321, call; 321, 322; 321, 325; 322, attribute; 322, 323; 322, 324; 323, string:"Done making a bib-coupling network from {}"; 324, identifier:format; 325, argument_list; 325, 326; 326, identifier:self; 327, return_statement; 327, 328; 328, identifier:workingGrph
def networkBibCoupling(self, weighted = True, fullInfo = False, addCR = False): """Creates a bibliographic coupling network based on citations for the RecordCollection. # Parameters _weighted_ : `optional bool` > Default `True`, if `True` the weight of the edges will be added to the network _fullInfo_ : `optional bool` > Default `False`, if `True` the full citation string will be added to each of the nodes of the network. # Returns `Networkx Graph` > A graph of the bibliographic coupling """ progArgs = (0, "Make a citation network for coupling") if metaknowledge.VERBOSE_MODE: progKwargs = {'dummy' : False} else: progKwargs = {'dummy' : True} with _ProgressBar(*progArgs, **progKwargs) as PBar: citeGrph = self.networkCitation(weighted = False, directed = True, detailedCore = True, fullInfo = fullInfo, count = False, nodeInfo = True, addCR = addCR, _quiet = True) pcount = 0 pmax = len(citeGrph) PBar.updateVal(.2, "Starting to classify nodes") workingGrph = nx.Graph() couplingSet = set() for n, d in citeGrph.nodes(data = True): pcount += 1 PBar.updateVal(.2 + .4 * (pcount / pmax), "Classifying: {}".format(n)) if d['inCore']: workingGrph.add_node(n, **d) if citeGrph.in_degree(n) > 0: couplingSet.add(n) pcount = 0 pmax = len(couplingSet) for n in couplingSet: PBar.updateVal(.6 + .4 * (pcount / pmax), "Coupling: {}".format(n)) citesLst = list(citeGrph.in_edges(n)) for i, edgeOuter in enumerate(citesLst): outerNode = edgeOuter[0] for edgeInner in citesLst[i + 1:]: innerNode = edgeInner[0] if weighted and workingGrph.has_edge(outerNode, innerNode): workingGrph.edges[outerNode, innerNode]['weight'] += 1 elif weighted: workingGrph.add_edge(outerNode, innerNode, weight = 1) else: workingGrph.add_edge(outerNode, innerNode) PBar.finish("Done making a bib-coupling network from {}".format(self)) return workingGrph
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:localCiteStats; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:pandasFriendly; 7, False; 8, default_parameter; 8, 9; 8, 10; 9, identifier:keyType; 10, string:"citation"; 11, block; 11, 12; 11, 14; 11, 18; 11, 25; 11, 36; 11, 57; 11, 222; 12, expression_statement; 12, 13; 13, comment; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:count; 17, integer:0; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:recCount; 21, call; 21, 22; 21, 23; 22, identifier:len; 23, argument_list; 23, 24; 24, identifier:self; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:progArgs; 28, tuple; 28, 29; 28, 30; 29, integer:0; 30, call; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, string:"Starting to get the local stats on {}s."; 33, identifier:format; 34, argument_list; 34, 35; 35, identifier:keyType; 36, if_statement; 36, 37; 36, 40; 36, 48; 37, attribute; 37, 38; 37, 39; 38, identifier:metaknowledge; 39, identifier:VERBOSE_MODE; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:progKwargs; 44, dictionary; 44, 45; 45, pair; 45, 46; 45, 47; 46, string:'dummy'; 47, False; 48, else_clause; 48, 49; 49, block; 49, 50; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:progKwargs; 53, dictionary; 53, 54; 54, pair; 54, 55; 54, 56; 55, string:'dummy'; 56, True; 57, with_statement; 57, 58; 57, 70; 58, with_clause; 58, 59; 59, with_item; 59, 60; 60, as_pattern; 60, 61; 60, 68; 61, call; 61, 62; 61, 63; 62, identifier:_ProgressBar; 63, argument_list; 63, 64; 63, 66; 64, list_splat; 64, 65; 65, identifier:progArgs; 66, dictionary_splat; 66, 67; 67, identifier:progKwargs; 68, as_pattern_target; 68, 69; 69, identifier:PBar; 70, block; 70, 71; 70, 79; 70, 83; 70, 113; 70, 203; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:keyTypesLst; 74, list:["citation", "journal", "year", "author"]; 74, 75; 74, 76; 74, 77; 74, 78; 75, string:"citation"; 76, string:"journal"; 77, string:"year"; 78, string:"author"; 79, expression_statement; 79, 80; 80, assignment; 80, 81; 80, 82; 81, identifier:citesDict; 82, dictionary; 83, if_statement; 83, 84; 83, 87; 84, comparison_operator:not; 84, 85; 84, 86; 85, identifier:keyType; 86, identifier:keyTypesLst; 87, block; 87, 88; 88, raise_statement; 88, 89; 89, call; 89, 90; 89, 91; 90, identifier:TypeError; 91, argument_list; 91, 92; 92, call; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, string:"{} is not a valid key type, only '{}' or '{}' are."; 95, identifier:format; 96, argument_list; 96, 97; 96, 98; 96, 109; 97, identifier:keyType; 98, call; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, string:"', '"; 101, identifier:join; 102, argument_list; 102, 103; 103, subscript; 103, 104; 103, 105; 104, identifier:keyTypesLst; 105, slice; 105, 106; 105, 107; 106, colon; 107, unary_operator:-; 107, 108; 108, integer:1; 109, subscript; 109, 110; 109, 111; 110, identifier:keyTypesLst; 111, unary_operator:-; 111, 112; 112, integer:1; 113, for_statement; 113, 114; 113, 115; 113, 116; 114, identifier:R; 115, identifier:self; 116, block; 116, 117; 116, 126; 116, 150; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:rCites; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:R; 123, identifier:get; 124, argument_list; 124, 125; 125, string:'citations'; 126, if_statement; 126, 127; 126, 128; 127, identifier:PBar; 128, block; 128, 129; 128, 133; 129, expression_statement; 129, 130; 130, augmented_assignment:+=; 130, 131; 130, 132; 131, identifier:count; 132, integer:1; 133, expression_statement; 133, 134; 134, call; 134, 135; 134, 138; 135, attribute; 135, 136; 135, 137; 136, identifier:PBar; 137, identifier:updateVal; 138, argument_list; 138, 139; 138, 142; 139, binary_operator:/; 139, 140; 139, 141; 140, identifier:count; 141, identifier:recCount; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, string:"Analysing: {}"; 145, identifier:format; 146, argument_list; 146, 147; 147, attribute; 147, 148; 147, 149; 148, identifier:R; 149, identifier:UT; 150, if_statement; 150, 151; 150, 152; 151, identifier:rCites; 152, block; 152, 153; 153, for_statement; 153, 154; 153, 155; 153, 156; 154, identifier:c; 155, identifier:rCites; 156, block; 156, 157; 156, 184; 157, if_statement; 157, 158; 157, 163; 157, 168; 158, comparison_operator:==; 158, 159; 158, 160; 159, identifier:keyType; 160, subscript; 160, 161; 160, 162; 161, identifier:keyTypesLst; 162, integer:0; 163, block; 163, 164; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 167; 166, identifier:cVal; 167, identifier:c; 168, else_clause; 168, 169; 169, block; 169, 170; 169, 178; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:cVal; 173, call; 173, 174; 173, 175; 174, identifier:getattr; 175, argument_list; 175, 176; 175, 177; 176, identifier:c; 177, identifier:keyType; 178, if_statement; 178, 179; 178, 182; 179, comparison_operator:is; 179, 180; 179, 181; 180, identifier:cVal; 181, None; 182, block; 182, 183; 183, continue_statement; 184, if_statement; 184, 185; 184, 188; 184, 195; 185, comparison_operator:in; 185, 186; 185, 187; 186, identifier:cVal; 187, identifier:citesDict; 188, block; 188, 189; 189, expression_statement; 189, 190; 190, augmented_assignment:+=; 190, 191; 190, 194; 191, subscript; 191, 192; 191, 193; 192, identifier:citesDict; 193, identifier:cVal; 194, integer:1; 195, else_clause; 195, 196; 196, block; 196, 197; 197, expression_statement; 197, 198; 198, assignment; 198, 199; 198, 202; 199, subscript; 199, 200; 199, 201; 200, identifier:citesDict; 201, identifier:cVal; 202, integer:1; 203, if_statement; 203, 204; 203, 205; 204, identifier:PBar; 205, block; 205, 206; 206, expression_statement; 206, 207; 207, call; 207, 208; 207, 211; 208, attribute; 208, 209; 208, 210; 209, identifier:PBar; 210, identifier:finish; 211, argument_list; 211, 212; 212, call; 212, 213; 212, 216; 213, attribute; 213, 214; 213, 215; 214, string:"Done, {} {} fields analysed"; 215, identifier:format; 216, argument_list; 216, 217; 216, 221; 217, call; 217, 218; 217, 219; 218, identifier:len; 219, argument_list; 219, 220; 220, identifier:citesDict; 221, identifier:keyType; 222, if_statement; 222, 223; 222, 224; 222, 265; 223, identifier:pandasFriendly; 224, block; 224, 225; 224, 229; 224, 233; 224, 257; 225, expression_statement; 225, 226; 226, assignment; 226, 227; 226, 228; 227, identifier:citeLst; 228, list:[]; 229, expression_statement; 229, 230; 230, assignment; 230, 231; 230, 232; 231, identifier:countLst; 232, list:[]; 233, for_statement; 233, 234; 233, 237; 233, 242; 234, pattern_list; 234, 235; 234, 236; 235, identifier:cite; 236, identifier:occ; 237, call; 237, 238; 237, 241; 238, attribute; 238, 239; 238, 240; 239, identifier:citesDict; 240, identifier:items; 241, argument_list; 242, block; 242, 243; 242, 250; 243, expression_statement; 243, 244; 244, call; 244, 245; 244, 248; 245, attribute; 245, 246; 245, 247; 246, identifier:citeLst; 247, identifier:append; 248, argument_list; 248, 249; 249, identifier:cite; 250, expression_statement; 250, 251; 251, call; 251, 252; 251, 255; 252, attribute; 252, 253; 252, 254; 253, identifier:countLst; 254, identifier:append; 255, argument_list; 255, 256; 256, identifier:occ; 257, return_statement; 257, 258; 258, dictionary; 258, 259; 258, 262; 259, pair; 259, 260; 259, 261; 260, string:"Citations"; 261, identifier:citeLst; 262, pair; 262, 263; 262, 264; 263, string:"Counts"; 264, identifier:countLst; 265, else_clause; 265, 266; 266, block; 266, 267; 267, return_statement; 267, 268; 268, identifier:citesDict
def localCiteStats(self, pandasFriendly = False, keyType = "citation"): """Returns a dict with all the citations in the CR field as keys and the number of times they occur as the values # Parameters _pandasFriendly_ : `optional [bool]` > default `False`, makes the output be a dict with two keys one `'Citations'` is the citations the other is their occurrence counts as `'Counts'`. _keyType_ : `optional [str]` > default `'citation'`, the type of key to use for the dictionary, the valid strings are `'citation'`, `'journal'`, `'year'` or `'author'`. IF changed from `'citation'` all citations matching the requested option will be contracted and their counts added together. # Returns `dict[str, int or Citation : int]` > A dictionary with keys as given by _keyType_ and integers giving their rates of occurrence in the collection """ count = 0 recCount = len(self) progArgs = (0, "Starting to get the local stats on {}s.".format(keyType)) if metaknowledge.VERBOSE_MODE: progKwargs = {'dummy' : False} else: progKwargs = {'dummy' : True} with _ProgressBar(*progArgs, **progKwargs) as PBar: keyTypesLst = ["citation", "journal", "year", "author"] citesDict = {} if keyType not in keyTypesLst: raise TypeError("{} is not a valid key type, only '{}' or '{}' are.".format(keyType, "', '".join(keyTypesLst[:-1]), keyTypesLst[-1])) for R in self: rCites = R.get('citations') if PBar: count += 1 PBar.updateVal(count / recCount, "Analysing: {}".format(R.UT)) if rCites: for c in rCites: if keyType == keyTypesLst[0]: cVal = c else: cVal = getattr(c, keyType) if cVal is None: continue if cVal in citesDict: citesDict[cVal] += 1 else: citesDict[cVal] = 1 if PBar: PBar.finish("Done, {} {} fields analysed".format(len(citesDict), keyType)) if pandasFriendly: citeLst = [] countLst = [] for cite, occ in citesDict.items(): citeLst.append(cite) countLst.append(occ) return {"Citations" : citeLst, "Counts" : countLst} else: return citesDict
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:citeFilter; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:keyString; 7, string:''; 8, default_parameter; 8, 9; 8, 10; 9, identifier:field; 10, string:'all'; 11, default_parameter; 11, 12; 11, 13; 12, identifier:reverse; 13, False; 14, default_parameter; 14, 15; 14, 16; 15, identifier:caseSensitive; 16, False; 17, block; 17, 18; 17, 20; 17, 24; 17, 31; 17, 391; 18, expression_statement; 18, 19; 19, comment; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:retRecs; 23, list:[]; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:keyString; 27, call; 27, 28; 27, 29; 28, identifier:str; 29, argument_list; 29, 30; 30, identifier:keyString; 31, for_statement; 31, 32; 31, 33; 31, 34; 32, identifier:R; 33, identifier:self; 34, block; 34, 35; 35, try_statement; 35, 36; 35, 387; 36, block; 36, 37; 37, if_statement; 37, 38; 37, 41; 37, 94; 37, 137; 37, 176; 37, 214; 37, 253; 37, 292; 37, 331; 37, 360; 38, comparison_operator:==; 38, 39; 38, 40; 39, identifier:field; 40, string:'all'; 41, block; 41, 42; 42, for_statement; 42, 43; 42, 44; 42, 50; 43, identifier:cite; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:R; 47, identifier:get; 48, argument_list; 48, 49; 49, string:'citations'; 50, block; 50, 51; 51, if_statement; 51, 52; 51, 53; 51, 69; 52, identifier:caseSensitive; 53, block; 53, 54; 54, if_statement; 54, 55; 54, 60; 55, comparison_operator:in; 55, 56; 55, 57; 56, identifier:keyString; 57, attribute; 57, 58; 57, 59; 58, identifier:cite; 59, identifier:original; 60, block; 60, 61; 60, 68; 61, expression_statement; 61, 62; 62, call; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:retRecs; 65, identifier:append; 66, argument_list; 66, 67; 67, identifier:R; 68, break_statement; 69, else_clause; 69, 70; 70, block; 70, 71; 71, if_statement; 71, 72; 71, 85; 72, comparison_operator:in; 72, 73; 72, 78; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:keyString; 76, identifier:upper; 77, argument_list; 78, call; 78, 79; 78, 84; 79, attribute; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:cite; 82, identifier:original; 83, identifier:upper; 84, argument_list; 85, block; 85, 86; 85, 93; 86, expression_statement; 86, 87; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:retRecs; 90, identifier:append; 91, argument_list; 91, 92; 92, identifier:R; 93, break_statement; 94, elif_clause; 94, 95; 94, 98; 95, comparison_operator:==; 95, 96; 95, 97; 96, identifier:field; 97, string:'author'; 98, block; 98, 99; 99, for_statement; 99, 100; 99, 101; 99, 107; 100, identifier:cite; 101, call; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:R; 104, identifier:get; 105, argument_list; 105, 106; 106, string:'citations'; 107, block; 107, 108; 108, try_statement; 108, 109; 108, 133; 109, block; 109, 110; 110, if_statement; 110, 111; 110, 124; 111, comparison_operator:in; 111, 112; 111, 117; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:keyString; 115, identifier:upper; 116, argument_list; 117, call; 117, 118; 117, 123; 118, attribute; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:cite; 121, identifier:author; 122, identifier:upper; 123, argument_list; 124, block; 124, 125; 124, 132; 125, expression_statement; 125, 126; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:retRecs; 129, identifier:append; 130, argument_list; 130, 131; 131, identifier:R; 132, break_statement; 133, except_clause; 133, 134; 133, 135; 134, identifier:AttributeError; 135, block; 135, 136; 136, pass_statement; 137, elif_clause; 137, 138; 137, 141; 138, comparison_operator:==; 138, 139; 138, 140; 139, identifier:field; 140, string:'journal'; 141, block; 141, 142; 142, for_statement; 142, 143; 142, 144; 142, 150; 143, identifier:cite; 144, call; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:R; 147, identifier:get; 148, argument_list; 148, 149; 149, string:'citations'; 150, block; 150, 151; 151, try_statement; 151, 152; 151, 172; 152, block; 152, 153; 153, if_statement; 153, 154; 153, 163; 154, comparison_operator:in; 154, 155; 154, 160; 155, call; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:keyString; 158, identifier:upper; 159, argument_list; 160, attribute; 160, 161; 160, 162; 161, identifier:cite; 162, identifier:journal; 163, block; 163, 164; 163, 171; 164, expression_statement; 164, 165; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:retRecs; 168, identifier:append; 169, argument_list; 169, 170; 170, identifier:R; 171, break_statement; 172, except_clause; 172, 173; 172, 174; 173, identifier:AttributeError; 174, block; 174, 175; 175, pass_statement; 176, elif_clause; 176, 177; 176, 180; 177, comparison_operator:==; 177, 178; 177, 179; 178, identifier:field; 179, string:'year'; 180, block; 180, 181; 181, for_statement; 181, 182; 181, 183; 181, 189; 182, identifier:cite; 183, call; 183, 184; 183, 187; 184, attribute; 184, 185; 184, 186; 185, identifier:R; 186, identifier:get; 187, argument_list; 187, 188; 188, string:'citations'; 189, block; 189, 190; 190, try_statement; 190, 191; 190, 210; 191, block; 191, 192; 192, if_statement; 192, 193; 192, 201; 193, comparison_operator:==; 193, 194; 193, 198; 194, call; 194, 195; 194, 196; 195, identifier:int; 196, argument_list; 196, 197; 197, identifier:keyString; 198, attribute; 198, 199; 198, 200; 199, identifier:cite; 200, identifier:year; 201, block; 201, 202; 201, 209; 202, expression_statement; 202, 203; 203, call; 203, 204; 203, 207; 204, attribute; 204, 205; 204, 206; 205, identifier:retRecs; 206, identifier:append; 207, argument_list; 207, 208; 208, identifier:R; 209, break_statement; 210, except_clause; 210, 211; 210, 212; 211, identifier:AttributeError; 212, block; 212, 213; 213, pass_statement; 214, elif_clause; 214, 215; 214, 218; 215, comparison_operator:==; 215, 216; 215, 217; 216, identifier:field; 217, string:'V'; 218, block; 218, 219; 219, for_statement; 219, 220; 219, 221; 219, 227; 220, identifier:cite; 221, call; 221, 222; 221, 225; 222, attribute; 222, 223; 222, 224; 223, identifier:R; 224, identifier:get; 225, argument_list; 225, 226; 226, string:'citations'; 227, block; 227, 228; 228, try_statement; 228, 229; 228, 249; 229, block; 229, 230; 230, if_statement; 230, 231; 230, 240; 231, comparison_operator:in; 231, 232; 231, 237; 232, call; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:keyString; 235, identifier:upper; 236, argument_list; 237, attribute; 237, 238; 237, 239; 238, identifier:cite; 239, identifier:V; 240, block; 240, 241; 240, 248; 241, expression_statement; 241, 242; 242, call; 242, 243; 242, 246; 243, attribute; 243, 244; 243, 245; 244, identifier:retRecs; 245, identifier:append; 246, argument_list; 246, 247; 247, identifier:R; 248, break_statement; 249, except_clause; 249, 250; 249, 251; 250, identifier:AttributeError; 251, block; 251, 252; 252, pass_statement; 253, elif_clause; 253, 254; 253, 257; 254, comparison_operator:==; 254, 255; 254, 256; 255, identifier:field; 256, string:'P'; 257, block; 257, 258; 258, for_statement; 258, 259; 258, 260; 258, 266; 259, identifier:cite; 260, call; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, identifier:R; 263, identifier:get; 264, argument_list; 264, 265; 265, string:'citations'; 266, block; 266, 267; 267, try_statement; 267, 268; 267, 288; 268, block; 268, 269; 269, if_statement; 269, 270; 269, 279; 270, comparison_operator:in; 270, 271; 270, 276; 271, call; 271, 272; 271, 275; 272, attribute; 272, 273; 272, 274; 273, identifier:keyString; 274, identifier:upper; 275, argument_list; 276, attribute; 276, 277; 276, 278; 277, identifier:cite; 278, identifier:P; 279, block; 279, 280; 279, 287; 280, expression_statement; 280, 281; 281, call; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:retRecs; 284, identifier:append; 285, argument_list; 285, 286; 286, identifier:R; 287, break_statement; 288, except_clause; 288, 289; 288, 290; 289, identifier:AttributeError; 290, block; 290, 291; 291, pass_statement; 292, elif_clause; 292, 293; 292, 296; 293, comparison_operator:==; 293, 294; 293, 295; 294, identifier:field; 295, string:'misc'; 296, block; 296, 297; 297, for_statement; 297, 298; 297, 299; 297, 305; 298, identifier:cite; 299, call; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, identifier:R; 302, identifier:get; 303, argument_list; 303, 304; 304, string:'citations'; 305, block; 305, 306; 306, try_statement; 306, 307; 306, 327; 307, block; 307, 308; 308, if_statement; 308, 309; 308, 318; 309, comparison_operator:in; 309, 310; 309, 315; 310, call; 310, 311; 310, 314; 311, attribute; 311, 312; 311, 313; 312, identifier:keyString; 313, identifier:upper; 314, argument_list; 315, attribute; 315, 316; 315, 317; 316, identifier:cite; 317, identifier:misc; 318, block; 318, 319; 318, 326; 319, expression_statement; 319, 320; 320, call; 320, 321; 320, 324; 321, attribute; 321, 322; 321, 323; 322, identifier:retRecs; 323, identifier:append; 324, argument_list; 324, 325; 325, identifier:R; 326, break_statement; 327, except_clause; 327, 328; 327, 329; 328, identifier:AttributeError; 329, block; 329, 330; 330, pass_statement; 331, elif_clause; 331, 332; 331, 335; 332, comparison_operator:==; 332, 333; 332, 334; 333, identifier:field; 334, string:'anonymous'; 335, block; 335, 336; 336, for_statement; 336, 337; 336, 338; 336, 344; 337, identifier:cite; 338, call; 338, 339; 338, 342; 339, attribute; 339, 340; 339, 341; 340, identifier:R; 341, identifier:get; 342, argument_list; 342, 343; 343, string:'citations'; 344, block; 344, 345; 345, if_statement; 345, 346; 345, 351; 346, call; 346, 347; 346, 350; 347, attribute; 347, 348; 347, 349; 348, identifier:cite; 349, identifier:isAnonymous; 350, argument_list; 351, block; 351, 352; 351, 359; 352, expression_statement; 352, 353; 353, call; 353, 354; 353, 357; 354, attribute; 354, 355; 354, 356; 355, identifier:retRecs; 356, identifier:append; 357, argument_list; 357, 358; 358, identifier:R; 359, break_statement; 360, elif_clause; 360, 361; 360, 364; 361, comparison_operator:==; 361, 362; 361, 363; 362, identifier:field; 363, string:'bad'; 364, block; 364, 365; 365, for_statement; 365, 366; 365, 367; 365, 373; 366, identifier:cite; 367, call; 367, 368; 367, 371; 368, attribute; 368, 369; 368, 370; 369, identifier:R; 370, identifier:get; 371, argument_list; 371, 372; 372, string:'citations'; 373, block; 373, 374; 374, if_statement; 374, 375; 374, 378; 375, attribute; 375, 376; 375, 377; 376, identifier:cite; 377, identifier:bad; 378, block; 378, 379; 378, 386; 379, expression_statement; 379, 380; 380, call; 380, 381; 380, 384; 381, attribute; 381, 382; 381, 383; 382, identifier:retRecs; 383, identifier:append; 384, argument_list; 384, 385; 385, identifier:R; 386, break_statement; 387, except_clause; 387, 388; 387, 389; 388, identifier:TypeError; 389, block; 389, 390; 390, pass_statement; 391, if_statement; 391, 392; 391, 393; 391, 429; 392, identifier:reverse; 393, block; 393, 394; 393, 398; 393, 414; 394, expression_statement; 394, 395; 395, assignment; 395, 396; 395, 397; 396, identifier:excluded; 397, list:[]; 398, for_statement; 398, 399; 398, 400; 398, 401; 399, identifier:R; 400, identifier:self; 401, block; 401, 402; 402, if_statement; 402, 403; 402, 406; 403, comparison_operator:not; 403, 404; 403, 405; 404, identifier:R; 405, identifier:retRecs; 406, block; 406, 407; 407, expression_statement; 407, 408; 408, call; 408, 409; 408, 412; 409, attribute; 409, 410; 409, 411; 410, identifier:excluded; 411, identifier:append; 412, argument_list; 412, 413; 413, identifier:R; 414, return_statement; 414, 415; 415, call; 415, 416; 415, 417; 416, identifier:RecordCollection; 417, argument_list; 417, 418; 417, 421; 417, 426; 418, keyword_argument; 418, 419; 418, 420; 419, identifier:inCollection; 420, identifier:excluded; 421, keyword_argument; 421, 422; 421, 423; 422, identifier:name; 423, attribute; 423, 424; 423, 425; 424, identifier:self; 425, identifier:name; 426, keyword_argument; 426, 427; 426, 428; 427, identifier:quietStart; 428, True; 429, else_clause; 429, 430; 430, block; 430, 431; 431, return_statement; 431, 432; 432, call; 432, 433; 432, 434; 433, identifier:RecordCollection; 434, argument_list; 434, 435; 434, 438; 434, 443; 435, keyword_argument; 435, 436; 435, 437; 436, identifier:inCollection; 437, identifier:retRecs; 438, keyword_argument; 438, 439; 438, 440; 439, identifier:name; 440, attribute; 440, 441; 440, 442; 441, identifier:self; 442, identifier:name; 443, keyword_argument; 443, 444; 443, 445; 444, identifier:quietStart; 445, True
def citeFilter(self, keyString = '', field = 'all', reverse = False, caseSensitive = False): """Filters `Records` by some string, _keyString_, in their citations and returns all `Records` with at least one citation possessing _keyString_ in the field given by _field_. # Parameters _keyString_ : `optional [str]` > Default `''`, gives the string to be searched for, if it is is blank then all citations with the specified field will be matched _field_ : `optional [str]` > Default `'all'`, gives the component of the citation to be looked at, it can be one of a few strings. The default is `'all'` which will cause the entire original `Citation` to be searched. It can be used to search across fields, e.g. `'1970, V2'` is a valid keystring The other options are: + `'author'`, searches the author field + `'year'`, searches the year field + `'journal'`, searches the journal field + `'V'`, searches the volume field + `'P'`, searches the page field + `'misc'`, searches all the remaining uncategorized information + `'anonymous'`, searches for anonymous `Citations`, _keyString_ is not ignored + `'bad'`, searches for bad citations, keyString is not used _reverse_ : `optional [bool]` > Default `False`, being set to `True` causes all `Records` not matching the query to be returned _caseSensitive_ : `optional [bool]` > Default `False`, if `True` causes the search across the original to be case sensitive, **only** the `'all'` option can be case sensitive """ retRecs = [] keyString = str(keyString) for R in self: try: if field == 'all': for cite in R.get('citations'): if caseSensitive: if keyString in cite.original: retRecs.append(R) break else: if keyString.upper() in cite.original.upper(): retRecs.append(R) break elif field == 'author': for cite in R.get('citations'): try: if keyString.upper() in cite.author.upper(): retRecs.append(R) break except AttributeError: pass elif field == 'journal': for cite in R.get('citations'): try: if keyString.upper() in cite.journal: retRecs.append(R) break except AttributeError: pass elif field == 'year': for cite in R.get('citations'): try: if int(keyString) == cite.year: retRecs.append(R) break except AttributeError: pass elif field == 'V': for cite in R.get('citations'): try: if keyString.upper() in cite.V: retRecs.append(R) break except AttributeError: pass elif field == 'P': for cite in R.get('citations'): try: if keyString.upper() in cite.P: retRecs.append(R) break except AttributeError: pass elif field == 'misc': for cite in R.get('citations'): try: if keyString.upper() in cite.misc: retRecs.append(R) break except AttributeError: pass elif field == 'anonymous': for cite in R.get('citations'): if cite.isAnonymous(): retRecs.append(R) break elif field == 'bad': for cite in R.get('citations'): if cite.bad: retRecs.append(R) break except TypeError: pass if reverse: excluded = [] for R in self: if R not in retRecs: excluded.append(R) return RecordCollection(inCollection = excluded, name = self.name, quietStart = True) else: return RecordCollection(inCollection = retRecs, name = self.name, quietStart = True)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 24; 2, function_name:rankedSeries; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 3, 21; 4, identifier:self; 5, identifier:tag; 6, default_parameter; 6, 7; 6, 8; 7, identifier:outputFile; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:giveCounts; 11, True; 12, default_parameter; 12, 13; 12, 14; 13, identifier:giveRanks; 14, False; 15, default_parameter; 15, 16; 15, 17; 16, identifier:greatestFirst; 17, True; 18, default_parameter; 18, 19; 18, 20; 19, identifier:pandasMode; 20, True; 21, default_parameter; 21, 22; 21, 23; 22, identifier:limitTo; 23, None; 24, block; 24, 25; 24, 27; 24, 37; 24, 41; 24, 102; 24, 124; 24, 172; 25, expression_statement; 25, 26; 26, comment; 27, if_statement; 27, 28; 27, 31; 28, boolean_operator:and; 28, 29; 28, 30; 29, identifier:giveRanks; 30, identifier:giveCounts; 31, block; 31, 32; 32, raise_statement; 32, 33; 33, call; 33, 34; 33, 35; 34, identifier:mkException; 35, argument_list; 35, 36; 36, string:"rankedSeries cannot return counts and ranks only one of giveRanks or giveCounts can be True."; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:seriesDict; 40, dictionary; 41, for_statement; 41, 42; 41, 43; 41, 44; 41, 45; 42, identifier:R; 43, identifier:self; 44, comment; 45, block; 45, 46; 45, 58; 45, 71; 46, try_statement; 46, 47; 46, 54; 47, block; 47, 48; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:val; 51, subscript; 51, 52; 51, 53; 52, identifier:R; 53, identifier:tag; 54, except_clause; 54, 55; 54, 56; 55, identifier:KeyError; 56, block; 56, 57; 57, continue_statement; 58, if_statement; 58, 59; 58, 65; 59, not_operator; 59, 60; 60, call; 60, 61; 60, 62; 61, identifier:isinstance; 62, argument_list; 62, 63; 62, 64; 63, identifier:val; 64, identifier:list; 65, block; 65, 66; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:val; 69, list:[val]; 69, 70; 70, identifier:val; 71, for_statement; 71, 72; 71, 73; 71, 74; 72, identifier:entry; 73, identifier:val; 74, block; 74, 75; 74, 83; 75, if_statement; 75, 76; 75, 81; 76, boolean_operator:and; 76, 77; 76, 78; 77, identifier:limitTo; 78, comparison_operator:not; 78, 79; 78, 80; 79, identifier:entry; 80, identifier:limitTo; 81, block; 81, 82; 82, continue_statement; 83, if_statement; 83, 84; 83, 87; 83, 94; 84, comparison_operator:in; 84, 85; 84, 86; 85, identifier:entry; 86, identifier:seriesDict; 87, block; 87, 88; 88, expression_statement; 88, 89; 89, augmented_assignment:+=; 89, 90; 89, 93; 90, subscript; 90, 91; 90, 92; 91, identifier:seriesDict; 92, identifier:entry; 93, integer:1; 94, else_clause; 94, 95; 95, block; 95, 96; 96, expression_statement; 96, 97; 97, assignment; 97, 98; 97, 101; 98, subscript; 98, 99; 98, 100; 99, identifier:seriesDict; 100, identifier:entry; 101, integer:1; 102, expression_statement; 102, 103; 103, assignment; 103, 104; 103, 105; 104, identifier:seriesList; 105, call; 105, 106; 105, 107; 106, identifier:sorted; 107, argument_list; 107, 108; 107, 113; 107, 121; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:seriesDict; 111, identifier:items; 112, argument_list; 113, keyword_argument; 113, 114; 113, 115; 114, identifier:key; 115, lambda; 115, 116; 115, 118; 116, lambda_parameters; 116, 117; 117, identifier:x; 118, subscript; 118, 119; 118, 120; 119, identifier:x; 120, integer:1; 121, keyword_argument; 121, 122; 121, 123; 122, identifier:reverse; 123, identifier:greatestFirst; 124, if_statement; 124, 125; 124, 128; 125, comparison_operator:is; 125, 126; 125, 127; 126, identifier:outputFile; 127, None; 128, block; 128, 129; 129, with_statement; 129, 130; 129, 140; 130, with_clause; 130, 131; 131, with_item; 131, 132; 132, as_pattern; 132, 133; 132, 138; 133, call; 133, 134; 133, 135; 134, identifier:open; 135, argument_list; 135, 136; 135, 137; 136, identifier:outputFile; 137, string:'w'; 138, as_pattern_target; 138, 139; 139, identifier:f; 140, block; 140, 141; 140, 153; 140, 165; 141, expression_statement; 141, 142; 142, assignment; 142, 143; 142, 144; 143, identifier:writer; 144, call; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:csv; 147, identifier:writer; 148, argument_list; 148, 149; 148, 150; 149, identifier:f; 150, keyword_argument; 150, 151; 150, 152; 151, identifier:dialect; 152, string:'excel'; 153, expression_statement; 153, 154; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:writer; 157, identifier:writerow; 158, argument_list; 158, 159; 159, tuple; 159, 160; 159, 164; 160, call; 160, 161; 160, 162; 161, identifier:str; 162, argument_list; 162, 163; 163, identifier:tag; 164, string:'count'; 165, expression_statement; 165, 166; 166, call; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:writer; 169, identifier:writerows; 170, argument_list; 170, 171; 171, identifier:seriesList; 172, if_statement; 172, 173; 172, 177; 172, 180; 172, 312; 173, boolean_operator:and; 173, 174; 173, 175; 174, identifier:giveCounts; 175, not_operator; 175, 176; 176, identifier:pandasMode; 177, block; 177, 178; 178, return_statement; 178, 179; 179, identifier:seriesList; 180, elif_clause; 180, 181; 180, 184; 181, boolean_operator:or; 181, 182; 181, 183; 182, identifier:giveRanks; 183, identifier:pandasMode; 184, block; 184, 185; 184, 195; 184, 199; 184, 203; 184, 216; 184, 293; 184, 303; 185, if_statement; 185, 186; 185, 188; 186, not_operator; 186, 187; 187, identifier:greatestFirst; 188, block; 188, 189; 189, expression_statement; 189, 190; 190, call; 190, 191; 190, 194; 191, attribute; 191, 192; 191, 193; 192, identifier:seriesList; 193, identifier:reverse; 194, argument_list; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:currentRank; 198, integer:1; 199, expression_statement; 199, 200; 200, assignment; 200, 201; 200, 202; 201, identifier:retList; 202, list:[]; 203, expression_statement; 203, 204; 204, assignment; 204, 205; 204, 206; 205, identifier:panDict; 206, dictionary; 206, 207; 206, 210; 206, 213; 207, pair; 207, 208; 207, 209; 208, string:'entry'; 209, list:[]; 210, pair; 210, 211; 210, 212; 211, string:'count'; 212, list:[]; 213, pair; 213, 214; 213, 215; 214, string:'rank'; 215, list:[]; 216, try_statement; 216, 217; 216, 226; 216, 231; 217, block; 217, 218; 218, expression_statement; 218, 219; 219, assignment; 219, 220; 219, 221; 220, identifier:currentCount; 221, subscript; 221, 222; 221, 225; 222, subscript; 222, 223; 222, 224; 223, identifier:seriesList; 224, integer:0; 225, integer:1; 226, except_clause; 226, 227; 226, 228; 226, 229; 227, identifier:IndexError; 228, comment; 229, block; 229, 230; 230, pass_statement; 231, else_clause; 231, 232; 232, block; 232, 233; 233, for_statement; 233, 234; 233, 237; 233, 238; 234, pattern_list; 234, 235; 234, 236; 235, identifier:valString; 236, identifier:count; 237, identifier:seriesList; 238, block; 238, 239; 238, 252; 239, if_statement; 239, 240; 239, 243; 240, comparison_operator:>; 240, 241; 240, 242; 241, identifier:currentCount; 242, identifier:count; 243, block; 243, 244; 243, 248; 244, expression_statement; 244, 245; 245, augmented_assignment:+=; 245, 246; 245, 247; 246, identifier:currentRank; 247, integer:1; 248, expression_statement; 248, 249; 249, assignment; 249, 250; 249, 251; 250, identifier:currentCount; 251, identifier:count; 252, if_statement; 252, 253; 252, 254; 252, 282; 253, identifier:pandasMode; 254, block; 254, 255; 254, 264; 254, 273; 255, expression_statement; 255, 256; 256, call; 256, 257; 256, 262; 257, attribute; 257, 258; 257, 261; 258, subscript; 258, 259; 258, 260; 259, identifier:panDict; 260, string:'entry'; 261, identifier:append; 262, argument_list; 262, 263; 263, identifier:valString; 264, expression_statement; 264, 265; 265, call; 265, 266; 265, 271; 266, attribute; 266, 267; 266, 270; 267, subscript; 267, 268; 267, 269; 268, identifier:panDict; 269, string:'count'; 270, identifier:append; 271, argument_list; 271, 272; 272, identifier:count; 273, expression_statement; 273, 274; 274, call; 274, 275; 274, 280; 275, attribute; 275, 276; 275, 279; 276, subscript; 276, 277; 276, 278; 277, identifier:panDict; 278, string:'rank'; 279, identifier:append; 280, argument_list; 280, 281; 281, identifier:currentRank; 282, else_clause; 282, 283; 283, block; 283, 284; 284, expression_statement; 284, 285; 285, call; 285, 286; 285, 289; 286, attribute; 286, 287; 286, 288; 287, identifier:retList; 288, identifier:append; 289, argument_list; 289, 290; 290, tuple; 290, 291; 290, 292; 291, identifier:valString; 292, identifier:currentRank; 293, if_statement; 293, 294; 293, 296; 294, not_operator; 294, 295; 295, identifier:greatestFirst; 296, block; 296, 297; 297, expression_statement; 297, 298; 298, call; 298, 299; 298, 302; 299, attribute; 299, 300; 299, 301; 300, identifier:retList; 301, identifier:reverse; 302, argument_list; 303, if_statement; 303, 304; 303, 305; 303, 308; 304, identifier:pandasMode; 305, block; 305, 306; 306, return_statement; 306, 307; 307, identifier:panDict; 308, else_clause; 308, 309; 309, block; 309, 310; 310, return_statement; 310, 311; 311, identifier:retList; 312, else_clause; 312, 313; 313, block; 313, 314; 314, return_statement; 314, 315; 315, list_comprehension; 315, 316; 315, 317; 316, identifier:e; 317, for_in_clause; 317, 318; 317, 321; 318, pattern_list; 318, 319; 318, 320; 319, identifier:e; 320, identifier:c; 321, identifier:seriesList
def rankedSeries(self, tag, outputFile = None, giveCounts = True, giveRanks = False, greatestFirst = True, pandasMode = True, limitTo = None): """Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by their number of occurrences. A list can also be returned with the the counts or ranks added or it can be written to a file. # Parameters _tag_ : `str` > The tag to be ranked _outputFile_ : `optional str` > A file path to write a csv with 2 columns, one the tag values the other their counts _giveCounts_ : `optional bool` > Default `True`, if `True` the retuned list will be composed of tuples the first values being the tag value and the second their counts. This supersedes _giveRanks_. _giveRanks_ : `optional bool` > Default `False`, if `True` and _giveCounts_ is `False`, the retuned list will be composed of tuples the first values being the tag value and the second their ranks. This is superseded by _giveCounts_. _greatestFirst_ : `optional bool` > Default `True`, if `True` the returned list will be ordered with the highest ranked value first, otherwise the lowest ranked will be first. _pandasMode_ : `optional bool` > Default `True`, if `True` a `dict` ready for pandas will be returned, otherwise a list _limitTo_ : `optional list[values]` > Default `None`, if a list is provided only those values in the list will be counted or returned # Returns `dict[str:list[value]] or list[str]` > A `dict` or `list` will be returned depending on if _pandasMode_ is `True` """ if giveRanks and giveCounts: raise mkException("rankedSeries cannot return counts and ranks only one of giveRanks or giveCounts can be True.") seriesDict = {} for R in self: #This should be faster than using get, since get is a wrapper for __getitem__ try: val = R[tag] except KeyError: continue if not isinstance(val, list): val = [val] for entry in val: if limitTo and entry not in limitTo: continue if entry in seriesDict: seriesDict[entry] += 1 else: seriesDict[entry] = 1 seriesList = sorted(seriesDict.items(), key = lambda x: x[1], reverse = greatestFirst) if outputFile is not None: with open(outputFile, 'w') as f: writer = csv.writer(f, dialect = 'excel') writer.writerow((str(tag), 'count')) writer.writerows(seriesList) if giveCounts and not pandasMode: return seriesList elif giveRanks or pandasMode: if not greatestFirst: seriesList.reverse() currentRank = 1 retList = [] panDict = {'entry' : [], 'count' : [], 'rank' : []} try: currentCount = seriesList[0][1] except IndexError: #Empty series so no need to loop pass else: for valString, count in seriesList: if currentCount > count: currentRank += 1 currentCount = count if pandasMode: panDict['entry'].append(valString) panDict['count'].append(count) panDict['rank'].append(currentRank) else: retList.append((valString, currentRank)) if not greatestFirst: retList.reverse() if pandasMode: return panDict else: return retList else: return [e for e,c in seriesList]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 23; 2, function_name:timeSeries; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:tag; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:outputFile; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:giveYears; 13, True; 14, default_parameter; 14, 15; 14, 16; 15, identifier:greatestFirst; 16, True; 17, default_parameter; 17, 18; 17, 19; 18, identifier:limitTo; 19, False; 20, default_parameter; 20, 21; 20, 22; 21, identifier:pandasMode; 22, True; 23, block; 23, 24; 23, 26; 23, 30; 23, 137; 23, 141; 23, 165; 23, 183; 23, 255; 24, expression_statement; 24, 25; 25, comment; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:seriesDict; 29, dictionary; 30, for_statement; 30, 31; 30, 32; 30, 33; 30, 34; 31, identifier:R; 32, identifier:self; 33, comment; 34, block; 34, 35; 34, 47; 35, try_statement; 35, 36; 35, 43; 36, block; 36, 37; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:year; 40, subscript; 40, 41; 40, 42; 41, identifier:R; 42, string:'year'; 43, except_clause; 43, 44; 43, 45; 44, identifier:KeyError; 45, block; 45, 46; 46, continue_statement; 47, if_statement; 47, 48; 47, 51; 47, 61; 48, comparison_operator:is; 48, 49; 48, 50; 49, identifier:tag; 50, None; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, assignment; 53, 54; 53, 57; 54, subscript; 54, 55; 54, 56; 55, identifier:seriesDict; 56, identifier:R; 57, dictionary; 57, 58; 58, pair; 58, 59; 58, 60; 59, identifier:year; 60, integer:1; 61, else_clause; 61, 62; 62, block; 62, 63; 62, 75; 62, 88; 63, try_statement; 63, 64; 63, 71; 64, block; 64, 65; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:val; 68, subscript; 68, 69; 68, 70; 69, identifier:R; 70, identifier:tag; 71, except_clause; 71, 72; 71, 73; 72, identifier:KeyError; 73, block; 73, 74; 74, continue_statement; 75, if_statement; 75, 76; 75, 82; 76, not_operator; 76, 77; 77, call; 77, 78; 77, 79; 78, identifier:isinstance; 79, argument_list; 79, 80; 79, 81; 80, identifier:val; 81, identifier:list; 82, block; 82, 83; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:val; 86, list:[val]; 86, 87; 87, identifier:val; 88, for_statement; 88, 89; 88, 90; 88, 91; 89, identifier:entry; 90, identifier:val; 91, block; 91, 92; 91, 100; 92, if_statement; 92, 93; 92, 98; 93, boolean_operator:and; 93, 94; 93, 95; 94, identifier:limitTo; 95, comparison_operator:not; 95, 96; 95, 97; 96, identifier:entry; 97, identifier:limitTo; 98, block; 98, 99; 99, continue_statement; 100, if_statement; 100, 101; 100, 104; 100, 126; 101, comparison_operator:in; 101, 102; 101, 103; 102, identifier:entry; 103, identifier:seriesDict; 104, block; 104, 105; 105, try_statement; 105, 106; 105, 115; 106, block; 106, 107; 107, expression_statement; 107, 108; 108, augmented_assignment:+=; 108, 109; 108, 114; 109, subscript; 109, 110; 109, 113; 110, subscript; 110, 111; 110, 112; 111, identifier:seriesDict; 112, identifier:entry; 113, identifier:year; 114, integer:1; 115, except_clause; 115, 116; 115, 117; 116, identifier:KeyError; 117, block; 117, 118; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 125; 120, subscript; 120, 121; 120, 124; 121, subscript; 121, 122; 121, 123; 122, identifier:seriesDict; 123, identifier:entry; 124, identifier:year; 125, integer:1; 126, else_clause; 126, 127; 127, block; 127, 128; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 133; 130, subscript; 130, 131; 130, 132; 131, identifier:seriesDict; 132, identifier:entry; 133, dictionary; 133, 134; 134, pair; 134, 135; 134, 136; 135, identifier:year; 136, integer:1; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 140; 139, identifier:seriesList; 140, list:[]; 141, for_statement; 141, 142; 141, 145; 141, 150; 142, pattern_list; 142, 143; 142, 144; 143, identifier:e; 144, identifier:yd; 145, call; 145, 146; 145, 149; 146, attribute; 146, 147; 146, 148; 147, identifier:seriesDict; 148, identifier:items; 149, argument_list; 150, block; 150, 151; 151, expression_statement; 151, 152; 152, augmented_assignment:+=; 152, 153; 152, 154; 153, identifier:seriesList; 154, list_comprehension; 154, 155; 154, 158; 155, tuple; 155, 156; 155, 157; 156, identifier:e; 157, identifier:y; 158, for_in_clause; 158, 159; 158, 160; 159, identifier:y; 160, call; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:yd; 163, identifier:keys; 164, argument_list; 165, expression_statement; 165, 166; 166, assignment; 166, 167; 166, 168; 167, identifier:seriesList; 168, call; 168, 169; 168, 170; 169, identifier:sorted; 170, argument_list; 170, 171; 170, 172; 170, 180; 171, identifier:seriesList; 172, keyword_argument; 172, 173; 172, 174; 173, identifier:key; 174, lambda; 174, 175; 174, 177; 175, lambda_parameters; 175, 176; 176, identifier:x; 177, subscript; 177, 178; 177, 179; 178, identifier:x; 179, integer:1; 180, keyword_argument; 180, 181; 180, 182; 181, identifier:reverse; 182, identifier:greatestFirst; 183, if_statement; 183, 184; 183, 187; 184, comparison_operator:is; 184, 185; 184, 186; 185, identifier:outputFile; 186, None; 187, block; 187, 188; 188, with_statement; 188, 189; 188, 199; 189, with_clause; 189, 190; 190, with_item; 190, 191; 191, as_pattern; 191, 192; 191, 197; 192, call; 192, 193; 192, 194; 193, identifier:open; 194, argument_list; 194, 195; 194, 196; 195, identifier:outputFile; 196, string:'w'; 197, as_pattern_target; 197, 198; 198, identifier:f; 199, block; 199, 200; 199, 212; 199, 224; 200, expression_statement; 200, 201; 201, assignment; 201, 202; 201, 203; 202, identifier:writer; 203, call; 203, 204; 203, 207; 204, attribute; 204, 205; 204, 206; 205, identifier:csv; 206, identifier:writer; 207, argument_list; 207, 208; 207, 209; 208, identifier:f; 209, keyword_argument; 209, 210; 209, 211; 210, identifier:dialect; 211, string:'excel'; 212, expression_statement; 212, 213; 213, call; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:writer; 216, identifier:writerow; 217, argument_list; 217, 218; 218, tuple; 218, 219; 218, 223; 219, call; 219, 220; 219, 221; 220, identifier:str; 221, argument_list; 221, 222; 222, identifier:tag; 223, string:'years'; 224, expression_statement; 224, 225; 225, call; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:writer; 228, identifier:writerows; 229, argument_list; 229, 230; 230, generator_expression; 230, 231; 230, 246; 231, tuple; 231, 232; 231, 233; 232, identifier:k; 233, call; 233, 234; 233, 237; 234, attribute; 234, 235; 234, 236; 235, string:'|'; 236, identifier:join; 237, argument_list; 237, 238; 238, generator_expression; 238, 239; 238, 243; 239, call; 239, 240; 239, 241; 240, identifier:str; 241, argument_list; 241, 242; 242, identifier:y; 243, for_in_clause; 243, 244; 243, 245; 244, identifier:y; 245, identifier:v; 246, for_in_clause; 246, 247; 246, 250; 247, pattern_list; 247, 248; 247, 249; 248, identifier:k; 249, identifier:v; 250, call; 250, 251; 250, 254; 251, attribute; 251, 252; 251, 253; 252, identifier:seriesDict; 253, identifier:items; 254, argument_list; 255, if_statement; 255, 256; 255, 257; 255, 310; 255, 315; 256, identifier:pandasMode; 257, block; 257, 258; 257, 271; 257, 308; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:panDict; 261, dictionary; 261, 262; 261, 265; 261, 268; 262, pair; 262, 263; 262, 264; 263, string:'entry'; 264, list:[]; 265, pair; 265, 266; 265, 267; 266, string:'count'; 267, list:[]; 268, pair; 268, 269; 268, 270; 269, string:'year'; 270, list:[]; 271, for_statement; 271, 272; 271, 275; 271, 276; 272, pattern_list; 272, 273; 272, 274; 273, identifier:entry; 274, identifier:year; 275, identifier:seriesList; 276, block; 276, 277; 276, 286; 276, 295; 277, expression_statement; 277, 278; 278, call; 278, 279; 278, 284; 279, attribute; 279, 280; 279, 283; 280, subscript; 280, 281; 280, 282; 281, identifier:panDict; 282, string:'entry'; 283, identifier:append; 284, argument_list; 284, 285; 285, identifier:entry; 286, expression_statement; 286, 287; 287, call; 287, 288; 287, 293; 288, attribute; 288, 289; 288, 292; 289, subscript; 289, 290; 289, 291; 290, identifier:panDict; 291, string:'year'; 292, identifier:append; 293, argument_list; 293, 294; 294, identifier:year; 295, expression_statement; 295, 296; 296, call; 296, 297; 296, 302; 297, attribute; 297, 298; 297, 301; 298, subscript; 298, 299; 298, 300; 299, identifier:panDict; 300, string:'count'; 301, identifier:append; 302, argument_list; 302, 303; 303, subscript; 303, 304; 303, 307; 304, subscript; 304, 305; 304, 306; 305, identifier:seriesDict; 306, identifier:entry; 307, identifier:year; 308, return_statement; 308, 309; 309, identifier:panDict; 310, elif_clause; 310, 311; 310, 312; 311, identifier:giveYears; 312, block; 312, 313; 313, return_statement; 313, 314; 314, identifier:seriesList; 315, else_clause; 315, 316; 316, block; 316, 317; 317, return_statement; 317, 318; 318, list_comprehension; 318, 319; 318, 320; 319, identifier:e; 320, for_in_clause; 320, 321; 320, 324; 321, pattern_list; 321, 322; 321, 323; 322, identifier:e; 323, identifier:c; 324, identifier:seriesList
def timeSeries(self, tag = None, outputFile = None, giveYears = True, greatestFirst = True, limitTo = False, pandasMode = True): """Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by the year the occurred in, multiple year occurrences will create multiple entries. A list can also be returned with the the counts or years added or it can be written to a file. If no _tag_ is given the `Records` in the collection will be used # Parameters _tag_ : `optional str` > Default `None`, if provided the tag will be ordered _outputFile_ : `optional str` > A file path to write a csv with 2 columns, one the tag values the other their years _giveYears_ : `optional bool` > Default `True`, if `True` the retuned list will be composed of tuples the first values being the tag value and the second their years. _greatestFirst_ : `optional bool` > Default `True`, if `True` the returned list will be ordered with the highest years first, otherwise the lowest years will be first. _pandasMode_ : `optional bool` > Default `True`, if `True` a `dict` ready for pandas will be returned, otherwise a list _limitTo_ : `optional list[values]` > Default `None`, if a list is provided only those values in the list will be counted or returned # Returns `dict[str:list[value]] or list[str]` > A `dict` or `list` will be returned depending on if _pandasMode_ is `True` """ seriesDict = {} for R in self: #This should be faster than using get, since get is a wrapper for __getitem__ try: year = R['year'] except KeyError: continue if tag is None: seriesDict[R] = {year : 1} else: try: val = R[tag] except KeyError: continue if not isinstance(val, list): val = [val] for entry in val: if limitTo and entry not in limitTo: continue if entry in seriesDict: try: seriesDict[entry][year] += 1 except KeyError: seriesDict[entry][year] = 1 else: seriesDict[entry] = {year : 1} seriesList = [] for e, yd in seriesDict.items(): seriesList += [(e, y) for y in yd.keys()] seriesList = sorted(seriesList, key = lambda x: x[1], reverse = greatestFirst) if outputFile is not None: with open(outputFile, 'w') as f: writer = csv.writer(f, dialect = 'excel') writer.writerow((str(tag), 'years')) writer.writerows(((k,'|'.join((str(y) for y in v))) for k,v in seriesDict.items())) if pandasMode: panDict = {'entry' : [], 'count' : [], 'year' : []} for entry, year in seriesList: panDict['entry'].append(entry) panDict['year'].append(year) panDict['count'].append(seriesDict[entry][year]) return panDict elif giveYears: return seriesList else: return [e for e,c in seriesList]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:cooccurrenceCounts; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:keyTag; 6, list_splat_pattern; 6, 7; 7, identifier:countedTags; 8, block; 8, 9; 8, 11; 8, 29; 8, 42; 8, 64; 8, 68; 8, 85; 8, 106; 8, 269; 9, expression_statement; 9, 10; 10, comment; 11, if_statement; 11, 12; 11, 18; 12, not_operator; 12, 13; 13, call; 13, 14; 13, 15; 14, identifier:isinstance; 15, argument_list; 15, 16; 15, 17; 16, identifier:keyTag; 17, identifier:str; 18, block; 18, 19; 19, raise_statement; 19, 20; 20, call; 20, 21; 20, 22; 21, identifier:TagError; 22, argument_list; 22, 23; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, string:"'{}' is not a string it cannot be used as a tag."; 26, identifier:format; 27, argument_list; 27, 28; 28, identifier:keyTag; 29, if_statement; 29, 30; 29, 36; 30, comparison_operator:<; 30, 31; 30, 35; 31, call; 31, 32; 31, 33; 32, identifier:len; 33, argument_list; 33, 34; 34, identifier:countedTags; 35, integer:1; 36, block; 36, 37; 37, expression_statement; 37, 38; 38, call; 38, 39; 38, 40; 39, identifier:TagError; 40, argument_list; 40, 41; 41, string:"You need to provide atleast one tag"; 42, for_statement; 42, 43; 42, 44; 42, 45; 43, identifier:tag; 44, identifier:countedTags; 45, block; 45, 46; 46, if_statement; 46, 47; 46, 53; 47, not_operator; 47, 48; 48, call; 48, 49; 48, 50; 49, identifier:isinstance; 50, argument_list; 50, 51; 50, 52; 51, identifier:tag; 52, identifier:str; 53, block; 53, 54; 54, raise_statement; 54, 55; 55, call; 55, 56; 55, 57; 56, identifier:TagError; 57, argument_list; 57, 58; 58, call; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, string:"'{}' is not a string it cannot be used as a tag."; 61, identifier:format; 62, argument_list; 62, 63; 63, identifier:tag; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:occurenceDict; 67, dictionary; 68, expression_statement; 68, 69; 69, assignment; 69, 70; 69, 71; 70, identifier:progArgs; 71, tuple; 71, 72; 71, 73; 72, integer:0; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, string:"Starting to count the co-occurrences of '{}' and' {}'"; 76, identifier:format; 77, argument_list; 77, 78; 77, 79; 78, identifier:keyTag; 79, call; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, string:"','"; 82, identifier:join; 83, argument_list; 83, 84; 84, identifier:countedTags; 85, if_statement; 85, 86; 85, 89; 85, 97; 86, attribute; 86, 87; 86, 88; 87, identifier:metaknowledge; 88, identifier:VERBOSE_MODE; 89, block; 89, 90; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:progKwargs; 93, dictionary; 93, 94; 94, pair; 94, 95; 94, 96; 95, string:'dummy'; 96, False; 97, else_clause; 97, 98; 98, block; 98, 99; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:progKwargs; 102, dictionary; 102, 103; 103, pair; 103, 104; 103, 105; 104, string:'dummy'; 105, True; 106, with_statement; 106, 107; 106, 119; 107, with_clause; 107, 108; 108, with_item; 108, 109; 109, as_pattern; 109, 110; 109, 117; 110, call; 110, 111; 110, 112; 111, identifier:_ProgressBar; 112, argument_list; 112, 113; 112, 115; 113, list_splat; 113, 114; 114, identifier:progArgs; 115, dictionary_splat; 115, 116; 116, identifier:progKwargs; 117, as_pattern_target; 117, 118; 118, identifier:PBar; 119, block; 119, 120; 119, 251; 120, for_statement; 120, 121; 120, 124; 120, 128; 121, pattern_list; 121, 122; 121, 123; 122, identifier:i; 123, identifier:R; 124, call; 124, 125; 124, 126; 125, identifier:enumerate; 126, argument_list; 126, 127; 127, identifier:self; 128, block; 128, 129; 128, 147; 128, 156; 128, 162; 128, 175; 128, 190; 129, expression_statement; 129, 130; 130, call; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:PBar; 133, identifier:updateVal; 134, argument_list; 134, 135; 134, 141; 135, binary_operator:/; 135, 136; 135, 137; 136, identifier:i; 137, call; 137, 138; 137, 139; 138, identifier:len; 139, argument_list; 139, 140; 140, identifier:self; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, string:"Analyzing {}"; 144, identifier:format; 145, argument_list; 145, 146; 146, identifier:R; 147, expression_statement; 147, 148; 148, assignment; 148, 149; 148, 150; 149, identifier:keyVal; 150, call; 150, 151; 150, 154; 151, attribute; 151, 152; 151, 153; 152, identifier:R; 153, identifier:get; 154, argument_list; 154, 155; 155, identifier:keyTag; 156, if_statement; 156, 157; 156, 160; 157, comparison_operator:is; 157, 158; 157, 159; 158, identifier:keyVal; 159, None; 160, block; 160, 161; 161, continue_statement; 162, if_statement; 162, 163; 162, 169; 163, not_operator; 163, 164; 164, call; 164, 165; 164, 166; 165, identifier:isinstance; 166, argument_list; 166, 167; 166, 168; 167, identifier:keyVal; 168, identifier:list; 169, block; 169, 170; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:keyVal; 173, list:[keyVal]; 173, 174; 174, identifier:keyVal; 175, for_statement; 175, 176; 175, 177; 175, 178; 176, identifier:key; 177, identifier:keyVal; 178, block; 178, 179; 179, if_statement; 179, 180; 179, 183; 180, comparison_operator:not; 180, 181; 180, 182; 181, identifier:key; 182, identifier:occurenceDict; 183, block; 183, 184; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 189; 186, subscript; 186, 187; 186, 188; 187, identifier:occurenceDict; 188, identifier:key; 189, dictionary; 190, for_statement; 190, 191; 190, 192; 190, 193; 191, identifier:tag; 192, identifier:countedTags; 193, block; 193, 194; 193, 203; 193, 209; 193, 222; 194, expression_statement; 194, 195; 195, assignment; 195, 196; 195, 197; 196, identifier:tagval; 197, call; 197, 198; 197, 201; 198, attribute; 198, 199; 198, 200; 199, identifier:R; 200, identifier:get; 201, argument_list; 201, 202; 202, identifier:tag; 203, if_statement; 203, 204; 203, 207; 204, comparison_operator:is; 204, 205; 204, 206; 205, identifier:tagval; 206, None; 207, block; 207, 208; 208, continue_statement; 209, if_statement; 209, 210; 209, 216; 210, not_operator; 210, 211; 211, call; 211, 212; 211, 213; 212, identifier:isinstance; 213, argument_list; 213, 214; 213, 215; 214, identifier:tagval; 215, identifier:list; 216, block; 216, 217; 217, expression_statement; 217, 218; 218, assignment; 218, 219; 218, 220; 219, identifier:tagval; 220, list:[tagval]; 220, 221; 221, identifier:tagval; 222, for_statement; 222, 223; 222, 224; 222, 225; 223, identifier:val; 224, identifier:tagval; 225, block; 225, 226; 226, for_statement; 226, 227; 226, 228; 226, 229; 227, identifier:key; 228, identifier:keyVal; 229, block; 229, 230; 230, try_statement; 230, 231; 230, 240; 231, block; 231, 232; 232, expression_statement; 232, 233; 233, augmented_assignment:+=; 233, 234; 233, 239; 234, subscript; 234, 235; 234, 238; 235, subscript; 235, 236; 235, 237; 236, identifier:occurenceDict; 237, identifier:key; 238, identifier:val; 239, integer:1; 240, except_clause; 240, 241; 240, 242; 241, identifier:KeyError; 242, block; 242, 243; 243, expression_statement; 243, 244; 244, assignment; 244, 245; 244, 250; 245, subscript; 245, 246; 245, 249; 246, subscript; 246, 247; 246, 248; 247, identifier:occurenceDict; 248, identifier:key; 249, identifier:val; 250, integer:1; 251, expression_statement; 251, 252; 252, call; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:PBar; 255, identifier:finish; 256, argument_list; 256, 257; 257, call; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, string:"Done extracting the co-occurrences of '{}' and '{}'"; 260, identifier:format; 261, argument_list; 261, 262; 261, 263; 262, identifier:keyTag; 263, call; 263, 264; 263, 267; 264, attribute; 264, 265; 264, 266; 265, string:"','"; 266, identifier:join; 267, argument_list; 267, 268; 268, identifier:countedTags; 269, return_statement; 269, 270; 270, identifier:occurenceDict
def cooccurrenceCounts(self, keyTag, *countedTags): """Counts the number of times values from any of the _countedTags_ occurs with _keyTag_. The counts are retuned as a dictionary with the values of _keyTag_ mapping to dictionaries with each of the _countedTags_ values mapping to thier counts. # Parameters _keyTag_ : `str` > The tag used as the key for the returned dictionary _*countedTags_ : `str, str, str, ...` > The tags used as the key for the returned dictionary's values # Returns `dict[str:dict[str:int]]` > The dictionary of counts """ if not isinstance(keyTag, str): raise TagError("'{}' is not a string it cannot be used as a tag.".format(keyTag)) if len(countedTags) < 1: TagError("You need to provide atleast one tag") for tag in countedTags: if not isinstance(tag, str): raise TagError("'{}' is not a string it cannot be used as a tag.".format(tag)) occurenceDict = {} progArgs = (0, "Starting to count the co-occurrences of '{}' and' {}'".format(keyTag, "','".join(countedTags))) if metaknowledge.VERBOSE_MODE: progKwargs = {'dummy' : False} else: progKwargs = {'dummy' : True} with _ProgressBar(*progArgs, **progKwargs) as PBar: for i, R in enumerate(self): PBar.updateVal(i / len(self), "Analyzing {}".format(R)) keyVal = R.get(keyTag) if keyVal is None: continue if not isinstance(keyVal, list): keyVal = [keyVal] for key in keyVal: if key not in occurenceDict: occurenceDict[key] = {} for tag in countedTags: tagval = R.get(tag) if tagval is None: continue if not isinstance(tagval, list): tagval = [tagval] for val in tagval: for key in keyVal: try: occurenceDict[key][val] += 1 except KeyError: occurenceDict[key][val] = 1 PBar.finish("Done extracting the co-occurrences of '{}' and '{}'".format(keyTag, "','".join(countedTags))) return occurenceDict
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 14; 2, function_name:getCitations; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:field; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:values; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:pandasFriendly; 13, True; 14, block; 14, 15; 14, 17; 14, 21; 14, 52; 14, 109; 14, 118; 15, expression_statement; 15, 16; 16, comment; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:retCites; 20, list:[]; 21, if_statement; 21, 22; 21, 25; 22, comparison_operator:is; 22, 23; 22, 24; 23, identifier:values; 24, None; 25, block; 25, 26; 26, if_statement; 26, 27; 26, 46; 27, boolean_operator:or; 27, 28; 27, 36; 28, call; 28, 29; 28, 30; 29, identifier:isinstance; 30, argument_list; 30, 31; 30, 32; 31, identifier:values; 32, tuple; 32, 33; 32, 34; 32, 35; 33, identifier:str; 34, identifier:int; 35, identifier:float; 36, not_operator; 36, 37; 37, call; 37, 38; 37, 39; 38, identifier:isinstance; 39, argument_list; 39, 40; 39, 41; 40, identifier:values; 41, attribute; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:collections; 44, identifier:abc; 45, identifier:Container; 46, block; 46, 47; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:values; 50, list:[values]; 50, 51; 51, identifier:values; 52, if_statement; 52, 53; 52, 56; 52, 97; 53, comparison_operator:is; 53, 54; 53, 55; 54, identifier:field; 55, None; 56, block; 56, 57; 57, for_statement; 57, 58; 57, 59; 57, 66; 58, identifier:cite; 59, call; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:self; 62, identifier:get; 63, argument_list; 63, 64; 63, 65; 64, string:'citations'; 65, list:[]; 66, block; 66, 67; 67, try_statement; 67, 68; 67, 93; 68, block; 68, 69; 68, 77; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:targetVal; 72, call; 72, 73; 72, 74; 73, identifier:getattr; 74, argument_list; 74, 75; 74, 76; 75, identifier:cite; 76, identifier:field; 77, if_statement; 77, 78; 77, 85; 78, boolean_operator:or; 78, 79; 78, 82; 79, comparison_operator:is; 79, 80; 79, 81; 80, identifier:values; 81, None; 82, comparison_operator:in; 82, 83; 82, 84; 83, identifier:targetVal; 84, identifier:values; 85, block; 85, 86; 86, expression_statement; 86, 87; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:retCites; 90, identifier:append; 91, argument_list; 91, 92; 92, identifier:cite; 93, except_clause; 93, 94; 93, 95; 94, identifier:AttributeError; 95, block; 95, 96; 96, pass_statement; 97, else_clause; 97, 98; 98, block; 98, 99; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:retCites; 102, call; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:self; 105, identifier:get; 106, argument_list; 106, 107; 106, 108; 107, string:'citations'; 108, list:[]; 109, if_statement; 109, 110; 109, 111; 110, identifier:pandasFriendly; 111, block; 111, 112; 112, return_statement; 112, 113; 113, call; 113, 114; 113, 115; 114, identifier:_pandasPrep; 115, argument_list; 115, 116; 115, 117; 116, identifier:retCites; 117, False; 118, return_statement; 118, 119; 119, identifier:retCites
def getCitations(self, field = None, values = None, pandasFriendly = True): """Creates a pandas ready dict with each row a different citation and columns containing the original string, year, journal and author's name. There are also options to filter the output citations with _field_ and _values_ # Parameters _field_ : `optional str` > Default `None`, if given all citations missing the named field will be dropped. _values_ : `optional str or list[str]` > Default `None`, if _field_ is also given only those citations with one of the strings given in _values_ will be included. > e.g. to get only citations from 1990 or 1991: `field = year, values = [1991, 1990]` _pandasFriendly_ : `optional bool` > Default `True`, if `False` a list of the citations will be returned instead of the more complicated pandas dict # Returns `dict` > A pandas ready dict with all the citations """ retCites = [] if values is not None: if isinstance(values, (str, int, float)) or not isinstance(values, collections.abc.Container): values = [values] if field is not None: for cite in self.get('citations', []): try: targetVal = getattr(cite, field) if values is None or targetVal in values: retCites.append(cite) except AttributeError: pass else: retCites = self.get('citations', []) if pandasFriendly: return _pandasPrep(retCites, False) return retCites
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:proQuestParser; 3, parameters; 3, 4; 4, identifier:proFile; 5, block; 5, 6; 5, 8; 5, 9; 5, 13; 5, 19; 5, 23; 5, 27; 5, 307; 6, expression_statement; 6, 7; 7, comment; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:nameDict; 12, dictionary; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:recSet; 16, call; 16, 17; 16, 18; 17, identifier:set; 18, argument_list; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:error; 22, None; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:lineNum; 26, integer:0; 27, try_statement; 27, 28; 27, 279; 28, block; 28, 29; 29, with_statement; 29, 30; 29, 43; 30, with_clause; 30, 31; 31, with_item; 31, 32; 32, as_pattern; 32, 33; 32, 41; 33, call; 33, 34; 33, 35; 34, identifier:open; 35, argument_list; 35, 36; 35, 37; 35, 38; 36, identifier:proFile; 37, string:'r'; 38, keyword_argument; 38, 39; 38, 40; 39, identifier:encoding; 40, string:'utf-8'; 41, as_pattern_target; 41, 42; 42, identifier:openfile; 43, block; 43, 44; 43, 54; 43, 70; 43, 71; 43, 150; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:f; 47, call; 47, 48; 47, 49; 48, identifier:enumerate; 49, argument_list; 49, 50; 49, 51; 50, identifier:openfile; 51, keyword_argument; 51, 52; 51, 53; 52, identifier:start; 53, integer:1; 54, for_statement; 54, 55; 54, 56; 54, 60; 55, identifier:i; 56, call; 56, 57; 56, 58; 57, identifier:range; 58, argument_list; 58, 59; 59, integer:12; 60, block; 60, 61; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 66; 63, pattern_list; 63, 64; 63, 65; 64, identifier:lineNum; 65, identifier:line; 66, call; 66, 67; 66, 68; 67, identifier:next; 68, argument_list; 68, 69; 69, identifier:f; 70, comment; 71, while_statement; 71, 72; 71, 73; 72, True; 73, block; 73, 74; 73, 83; 73, 92; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 79; 76, pattern_list; 76, 77; 76, 78; 77, identifier:lineNum; 78, identifier:line; 79, call; 79, 80; 79, 81; 80, identifier:next; 81, argument_list; 81, 82; 82, identifier:f; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 88; 85, pattern_list; 85, 86; 85, 87; 86, identifier:lineNum; 87, identifier:line; 88, call; 88, 89; 88, 90; 89, identifier:next; 90, argument_list; 90, 91; 91, identifier:f; 92, if_statement; 92, 93; 92, 96; 92, 114; 93, comparison_operator:==; 93, 94; 93, 95; 94, identifier:line; 95, string:'Bibliography\n'; 96, block; 96, 97; 96, 113; 97, for_statement; 97, 98; 97, 99; 97, 103; 98, identifier:i; 99, call; 99, 100; 99, 101; 100, identifier:range; 101, argument_list; 101, 102; 102, integer:3; 103, block; 103, 104; 104, expression_statement; 104, 105; 105, assignment; 105, 106; 105, 109; 106, pattern_list; 106, 107; 106, 108; 107, identifier:lineNum; 108, identifier:line; 109, call; 109, 110; 109, 111; 110, identifier:next; 111, argument_list; 111, 112; 112, identifier:f; 113, break_statement; 114, else_clause; 114, 115; 115, block; 115, 116; 115, 125; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:s; 119, call; 119, 120; 119, 123; 120, attribute; 120, 121; 120, 122; 121, identifier:line; 122, identifier:split; 123, argument_list; 123, 124; 124, string:'. '; 125, expression_statement; 125, 126; 126, assignment; 126, 127; 126, 135; 127, subscript; 127, 128; 127, 129; 128, identifier:nameDict; 129, call; 129, 130; 129, 131; 130, identifier:int; 131, argument_list; 131, 132; 132, subscript; 132, 133; 132, 134; 133, identifier:s; 134, integer:0; 135, subscript; 135, 136; 135, 146; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, string:'. '; 139, identifier:join; 140, argument_list; 140, 141; 141, subscript; 141, 142; 141, 143; 142, identifier:s; 143, slice; 143, 144; 143, 145; 144, integer:1; 145, colon; 146, slice; 146, 147; 146, 148; 147, colon; 148, unary_operator:-; 148, 149; 149, integer:1; 150, while_statement; 150, 151; 150, 152; 150, 153; 151, True; 152, comment; 153, block; 153, 154; 153, 163; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 159; 156, pattern_list; 156, 157; 156, 158; 157, identifier:lineNum; 158, identifier:line; 159, call; 159, 160; 159, 161; 160, identifier:next; 161, argument_list; 161, 162; 162, identifier:f; 163, if_statement; 163, 164; 163, 167; 163, 169; 163, 261; 164, comparison_operator:==; 164, 165; 164, 166; 165, identifier:line; 166, string:'Bibliography\n'; 167, block; 167, 168; 168, break_statement; 169, elif_clause; 169, 170; 169, 176; 170, call; 170, 171; 170, 174; 171, attribute; 171, 172; 171, 173; 172, identifier:line; 173, identifier:startswith; 174, argument_list; 174, 175; 175, string:'Document '; 176, block; 176, 177; 176, 195; 176, 208; 176, 245; 176, 252; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 180; 179, identifier:n; 180, call; 180, 181; 180, 182; 181, identifier:int; 182, argument_list; 182, 183; 183, subscript; 183, 184; 183, 194; 184, call; 184, 185; 184, 192; 185, attribute; 185, 186; 185, 191; 186, subscript; 186, 187; 186, 188; 187, identifier:line; 188, slice; 188, 189; 188, 190; 189, integer:9; 190, colon; 191, identifier:split; 192, argument_list; 192, 193; 193, string:' of '; 194, integer:0; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:R; 198, call; 198, 199; 198, 200; 199, identifier:ProQuestRecord; 200, argument_list; 200, 201; 200, 202; 200, 205; 201, identifier:f; 202, keyword_argument; 202, 203; 202, 204; 203, identifier:sFile; 204, identifier:proFile; 205, keyword_argument; 205, 206; 205, 207; 206, identifier:sLine; 207, identifier:lineNum; 208, if_statement; 208, 209; 208, 219; 209, comparison_operator:!=; 209, 210; 209, 216; 210, call; 210, 211; 210, 214; 211, attribute; 211, 212; 211, 213; 212, identifier:R; 213, identifier:get; 214, argument_list; 214, 215; 215, string:'Title'; 216, subscript; 216, 217; 216, 218; 217, identifier:nameDict; 218, identifier:n; 219, block; 219, 220; 219, 243; 220, expression_statement; 220, 221; 221, assignment; 221, 222; 221, 223; 222, identifier:error; 223, call; 223, 224; 223, 225; 224, identifier:BadProQuestFile; 225, argument_list; 225, 226; 226, call; 226, 227; 226, 230; 227, attribute; 227, 228; 227, 229; 228, string:"The numbering of the titles at the beginning of the file does not match the records inside. Line {} has a record titled '{}' with number {}, the name should be '{}'."; 229, identifier:format; 230, argument_list; 230, 231; 230, 232; 230, 239; 230, 240; 231, identifier:lineNum; 232, call; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:R; 235, identifier:get; 236, argument_list; 236, 237; 236, 238; 237, string:'Title'; 238, string:"TITLE MISSING"; 239, identifier:n; 240, subscript; 240, 241; 240, 242; 241, identifier:nameDict; 242, identifier:n; 243, raise_statement; 243, 244; 244, identifier:StopIteration; 245, expression_statement; 245, 246; 246, call; 246, 247; 246, 250; 247, attribute; 247, 248; 247, 249; 248, identifier:recSet; 249, identifier:add; 250, argument_list; 250, 251; 251, identifier:R; 252, expression_statement; 252, 253; 253, assignment; 253, 254; 253, 257; 254, pattern_list; 254, 255; 254, 256; 255, identifier:lineNum; 256, identifier:line; 257, call; 257, 258; 257, 259; 258, identifier:next; 259, argument_list; 259, 260; 260, identifier:f; 261, else_clause; 261, 262; 261, 263; 262, comment; 263, block; 263, 264; 263, 277; 264, expression_statement; 264, 265; 265, assignment; 265, 266; 265, 267; 266, identifier:error; 267, call; 267, 268; 267, 269; 268, identifier:BadProQuestFile; 269, argument_list; 269, 270; 270, call; 270, 271; 270, 274; 271, attribute; 271, 272; 271, 273; 272, string:"The file '{}' has parts of it that are unparsable starting at line: {}. It is likely that the seperators between the records are incorrect"; 273, identifier:format; 274, argument_list; 274, 275; 274, 276; 275, identifier:proFile; 276, identifier:lineNum; 277, raise_statement; 277, 278; 278, identifier:StopIteration; 279, except_clause; 279, 280; 279, 287; 280, as_pattern; 280, 281; 280, 285; 281, tuple; 281, 282; 281, 283; 281, 284; 282, identifier:UnicodeDecodeError; 283, identifier:StopIteration; 284, identifier:ValueError; 285, as_pattern_target; 285, 286; 286, identifier:e; 287, block; 287, 288; 288, if_statement; 288, 289; 288, 292; 289, comparison_operator:is; 289, 290; 289, 291; 290, identifier:error; 291, None; 292, block; 292, 293; 293, expression_statement; 293, 294; 294, assignment; 294, 295; 294, 296; 295, identifier:error; 296, call; 296, 297; 296, 298; 297, identifier:BadProQuestFile; 298, argument_list; 298, 299; 299, call; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, string:"The file '{}' has parts of it that are unparsable starting at line: {}.\nThe error was: '{}'"; 302, identifier:format; 303, argument_list; 303, 304; 303, 305; 303, 306; 304, identifier:proFile; 305, identifier:lineNum; 306, identifier:e; 307, return_statement; 307, 308; 308, expression_list; 308, 309; 308, 310; 309, identifier:recSet; 310, identifier:error
def proQuestParser(proFile): """Parses a ProQuest file, _proFile_, to extract the individual entries. A ProQuest file has three sections, first a list of the contained entries, second the full metadata and finally a bibtex formatted entry for the record. This parser only uses the first two as the bibtex contains no information the second section does not. Also, the first section is only used to verify the second section. The returned [ProQuestRecord](../classes/ProQuestRecord.html#metaknowledge.proquest.ProQuestRecord) contains the data from the second section, with the same key strings as ProQuest uses and the unlabeled sections are called in order, `'Name'`, `'Author'` and `'url'`. # Parameters _proFile_ : `str` > A path to a valid ProQuest file, use [isProQuestFile](#metaknowledge.proquest.proQuestHandlers.isProQuestFile) to verify # Returns `set[ProQuestRecord]` > Records for each of the entries """ #assumes the file is ProQuest nameDict = {} recSet = set() error = None lineNum = 0 try: with open(proFile, 'r', encoding = 'utf-8') as openfile: f = enumerate(openfile, start = 1) for i in range(12): lineNum, line = next(f) # f is file so it *should* end, or at least cause a parser error eventually while True: lineNum, line = next(f) lineNum, line = next(f) if line == 'Bibliography\n': for i in range(3): lineNum, line = next(f) break else: s = line.split('. ') nameDict[int(s[0])] = '. '.join(s[1:])[:-1] while True: #import pdb; pdb.set_trace() lineNum, line = next(f) if line == 'Bibliography\n': break elif line.startswith('Document '): n = int(line[9:].split(' of ')[0]) R = ProQuestRecord(f, sFile = proFile, sLine = lineNum) if R.get('Title') != nameDict[n]: error = BadProQuestFile("The numbering of the titles at the beginning of the file does not match the records inside. Line {} has a record titled '{}' with number {}, the name should be '{}'.".format(lineNum, R.get('Title', "TITLE MISSING"), n, nameDict[n])) raise StopIteration recSet.add(R) lineNum, line = next(f) else: #Parsing failed error = BadProQuestFile("The file '{}' has parts of it that are unparsable starting at line: {}. It is likely that the seperators between the records are incorrect".format(proFile, lineNum)) raise StopIteration except (UnicodeDecodeError, StopIteration, ValueError) as e: if error is None: error = BadProQuestFile("The file '{}' has parts of it that are unparsable starting at line: {}.\nThe error was: '{}'".format(proFile, lineNum, e)) return recSet, error
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:minus; 3, parameters; 3, 4; 3, 5; 4, identifier:repo_list_a; 5, identifier:repo_list_b; 6, block; 6, 7; 6, 9; 6, 17; 6, 29; 6, 35; 6, 62; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:included; 12, call; 12, 13; 12, 14; 13, identifier:defaultdict; 14, argument_list; 14, 15; 15, lambda; 15, 16; 16, False; 17, for_statement; 17, 18; 17, 19; 17, 20; 18, identifier:repo; 19, identifier:repo_list_b; 20, block; 20, 21; 21, expression_statement; 21, 22; 22, assignment; 22, 23; 22, 28; 23, subscript; 23, 24; 23, 25; 24, identifier:included; 25, attribute; 25, 26; 25, 27; 26, identifier:repo; 27, identifier:full_name; 28, True; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:a_minus_b; 32, call; 32, 33; 32, 34; 33, identifier:list; 34, argument_list; 35, for_statement; 35, 36; 35, 37; 35, 38; 36, identifier:repo; 37, identifier:repo_list_a; 38, block; 38, 39; 39, if_statement; 39, 40; 39, 46; 40, not_operator; 40, 41; 41, subscript; 41, 42; 41, 43; 42, identifier:included; 43, attribute; 43, 44; 43, 45; 44, identifier:repo; 45, identifier:full_name; 46, block; 46, 47; 46, 55; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 54; 49, subscript; 49, 50; 49, 51; 50, identifier:included; 51, attribute; 51, 52; 51, 53; 52, identifier:repo; 53, identifier:full_name; 54, True; 55, expression_statement; 55, 56; 56, call; 56, 57; 56, 60; 57, attribute; 57, 58; 57, 59; 58, identifier:a_minus_b; 59, identifier:append; 60, argument_list; 60, 61; 61, identifier:repo; 62, return_statement; 62, 63; 63, identifier:a_minus_b
def minus(repo_list_a, repo_list_b): """Method to create a list of repositories such that the repository belongs to repo list a but not repo list b. In an ideal scenario we should be able to do this by set(a) - set(b) but as GithubRepositories have shown that set() on them is not reliable resort to this until it is all sorted out. :param repo_list_a: List of repositories. :param repo_list_b: List of repositories. """ included = defaultdict(lambda: False) for repo in repo_list_b: included[repo.full_name] = True a_minus_b = list() for repo in repo_list_a: if not included[repo.full_name]: included[repo.full_name] = True a_minus_b.append(repo) return a_minus_b
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:__clean_and_tokenize; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:doc_list; 6, block; 6, 7; 6, 9; 6, 10; 6, 11; 6, 33; 6, 39; 6, 40; 6, 41; 6, 48; 6, 49; 6, 57; 6, 58; 6, 66; 6, 135; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:doc_list; 14, call; 14, 15; 14, 16; 15, identifier:filter; 16, argument_list; 16, 17; 16, 32; 17, lambda; 17, 18; 17, 20; 18, lambda_parameters; 18, 19; 19, identifier:x; 20, boolean_operator:and; 20, 21; 20, 24; 21, comparison_operator:is; 21, 22; 21, 23; 22, identifier:x; 23, None; 24, comparison_operator:<=; 24, 25; 24, 29; 25, call; 25, 26; 25, 27; 26, identifier:len; 27, argument_list; 27, 28; 28, identifier:x; 29, attribute; 29, 30; 29, 31; 30, identifier:GitSuggest; 31, identifier:MAX_DESC_LEN; 32, identifier:doc_list; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:cleaned_doc_list; 36, call; 36, 37; 36, 38; 37, identifier:list; 38, argument_list; 39, comment; 40, comment; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:tokenizer; 44, call; 44, 45; 44, 46; 45, identifier:RegexpTokenizer; 46, argument_list; 46, 47; 47, string:r"[a-zA-Z]+"; 48, comment; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:stopwords; 52, call; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:self; 55, identifier:__get_words_to_ignore; 56, argument_list; 57, comment; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 61; 60, identifier:dict_words; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:self; 64, identifier:__get_words_to_consider; 65, argument_list; 66, for_statement; 66, 67; 66, 68; 66, 69; 66, 70; 67, identifier:doc; 68, identifier:doc_list; 69, comment; 70, block; 70, 71; 70, 79; 70, 80; 70, 89; 70, 90; 70, 102; 70, 103; 70, 115; 70, 116; 70, 128; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:lower; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:doc; 77, identifier:lower; 78, argument_list; 79, comment; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:tokens; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:tokenizer; 86, identifier:tokenize; 87, argument_list; 87, 88; 88, identifier:lower; 89, comment; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 93; 92, identifier:tokens; 93, list_comprehension; 93, 94; 93, 95; 93, 98; 94, identifier:tok; 95, for_in_clause; 95, 96; 95, 97; 96, identifier:tok; 97, identifier:tokens; 98, if_clause; 98, 99; 99, comparison_operator:in; 99, 100; 99, 101; 100, identifier:tok; 101, identifier:dict_words; 102, comment; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:tokens; 106, list_comprehension; 106, 107; 106, 108; 106, 111; 107, identifier:tok; 108, for_in_clause; 108, 109; 108, 110; 109, identifier:tok; 110, identifier:tokens; 111, if_clause; 111, 112; 112, comparison_operator:not; 112, 113; 112, 114; 113, identifier:tok; 114, identifier:stopwords; 115, comment; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:tokens; 119, list_comprehension; 119, 120; 119, 121; 119, 124; 120, identifier:tok; 121, for_in_clause; 121, 122; 121, 123; 122, identifier:tok; 123, identifier:tokens; 124, if_clause; 124, 125; 125, comparison_operator:is; 125, 126; 125, 127; 126, identifier:tok; 127, None; 128, expression_statement; 128, 129; 129, call; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:cleaned_doc_list; 132, identifier:append; 133, argument_list; 133, 134; 134, identifier:tokens; 135, return_statement; 135, 136; 136, identifier:cleaned_doc_list
def __clean_and_tokenize(self, doc_list): """Method to clean and tokenize the document list. :param doc_list: Document list to clean and tokenize. :return: Cleaned and tokenized document list. """ # Some repositories fill entire documentation in description. We ignore # such repositories for cleaner tokens. doc_list = filter( lambda x: x is not None and len(x) <= GitSuggest.MAX_DESC_LEN, doc_list, ) cleaned_doc_list = list() # Regular expression to remove out all punctuations, numbers and other # un-necessary text substrings like emojis etc. tokenizer = RegexpTokenizer(r"[a-zA-Z]+") # Get stop words. stopwords = self.__get_words_to_ignore() # Get english words. dict_words = self.__get_words_to_consider() for doc in doc_list: # Lowercase doc. lower = doc.lower() # Tokenize removing numbers and punctuation. tokens = tokenizer.tokenize(lower) # Include meaningful words. tokens = [tok for tok in tokens if tok in dict_words] # Remove stopwords. tokens = [tok for tok in tokens if tok not in stopwords] # Filter Nones if any are introduced. tokens = [tok for tok in tokens if tok is not None] cleaned_doc_list.append(tokens) return cleaned_doc_list
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 10; 2, function_name:__get_search_results; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, identifier:self; 5, identifier:url; 6, identifier:limit; 7, identifier:order_by; 8, identifier:sort_order; 9, identifier:filter; 10, block; 10, 11; 10, 13; 10, 29; 10, 61; 10, 95; 10, 101; 10, 133; 10, 144; 10, 151; 10, 166; 10, 222; 11, expression_statement; 11, 12; 12, comment; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:order_by_options; 16, list:['search_rank', 'series_id', 'title', 'units', 'frequency', 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end', 'popularity']; 16, 17; 16, 18; 16, 19; 16, 20; 16, 21; 16, 22; 16, 23; 16, 24; 16, 25; 16, 26; 16, 27; 16, 28; 17, string:'search_rank'; 18, string:'series_id'; 19, string:'title'; 20, string:'units'; 21, string:'frequency'; 22, string:'seasonal_adjustment'; 23, string:'realtime_start'; 24, string:'realtime_end'; 25, string:'last_updated'; 26, string:'observation_start'; 27, string:'observation_end'; 28, string:'popularity'; 29, if_statement; 29, 30; 29, 33; 30, comparison_operator:is; 30, 31; 30, 32; 31, identifier:order_by; 32, None; 33, block; 33, 34; 34, if_statement; 34, 35; 34, 38; 34, 47; 35, comparison_operator:in; 35, 36; 35, 37; 36, identifier:order_by; 37, identifier:order_by_options; 38, block; 38, 39; 39, expression_statement; 39, 40; 40, assignment; 40, 41; 40, 42; 41, identifier:url; 42, binary_operator:+; 42, 43; 42, 46; 43, binary_operator:+; 43, 44; 43, 45; 44, identifier:url; 45, string:'&order_by='; 46, identifier:order_by; 47, else_clause; 47, 48; 48, block; 48, 49; 49, raise_statement; 49, 50; 50, call; 50, 51; 50, 52; 51, identifier:ValueError; 52, argument_list; 52, 53; 53, binary_operator:%; 53, 54; 53, 55; 54, string:'%s is not in the valid list of order_by options: %s'; 55, tuple; 55, 56; 55, 57; 56, identifier:order_by; 57, call; 57, 58; 57, 59; 58, identifier:str; 59, argument_list; 59, 60; 60, identifier:order_by_options; 61, if_statement; 61, 62; 61, 65; 62, comparison_operator:is; 62, 63; 62, 64; 63, identifier:filter; 64, None; 65, block; 65, 66; 66, if_statement; 66, 67; 66, 73; 66, 88; 67, comparison_operator:==; 67, 68; 67, 72; 68, call; 68, 69; 68, 70; 69, identifier:len; 70, argument_list; 70, 71; 71, identifier:filter; 72, integer:2; 73, block; 73, 74; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:url; 77, binary_operator:+; 77, 78; 77, 79; 78, identifier:url; 79, binary_operator:%; 79, 80; 79, 81; 80, string:'&filter_variable=%s&filter_value=%s'; 81, tuple; 81, 82; 81, 85; 82, subscript; 82, 83; 82, 84; 83, identifier:filter; 84, integer:0; 85, subscript; 85, 86; 85, 87; 86, identifier:filter; 87, integer:1; 88, else_clause; 88, 89; 89, block; 89, 90; 90, raise_statement; 90, 91; 91, call; 91, 92; 91, 93; 92, identifier:ValueError; 93, argument_list; 93, 94; 94, string:'Filter should be a 2 item tuple like (filter_variable, filter_value)'; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:sort_order_options; 98, list:['asc', 'desc']; 98, 99; 98, 100; 99, string:'asc'; 100, string:'desc'; 101, if_statement; 101, 102; 101, 105; 102, comparison_operator:is; 102, 103; 102, 104; 103, identifier:sort_order; 104, None; 105, block; 105, 106; 106, if_statement; 106, 107; 106, 110; 106, 119; 107, comparison_operator:in; 107, 108; 107, 109; 108, identifier:sort_order; 109, identifier:sort_order_options; 110, block; 110, 111; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:url; 114, binary_operator:+; 114, 115; 114, 118; 115, binary_operator:+; 115, 116; 115, 117; 116, identifier:url; 117, string:'&sort_order='; 118, identifier:sort_order; 119, else_clause; 119, 120; 120, block; 120, 121; 121, raise_statement; 121, 122; 122, call; 122, 123; 122, 124; 123, identifier:ValueError; 124, argument_list; 124, 125; 125, binary_operator:%; 125, 126; 125, 127; 126, string:'%s is not in the valid list of sort_order options: %s'; 127, tuple; 127, 128; 127, 129; 128, identifier:sort_order; 129, call; 129, 130; 129, 131; 130, identifier:str; 131, argument_list; 131, 132; 132, identifier:sort_order_options; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 138; 135, pattern_list; 135, 136; 135, 137; 136, identifier:data; 137, identifier:num_results_total; 138, call; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:self; 141, identifier:__do_series_search; 142, argument_list; 142, 143; 143, identifier:url; 144, if_statement; 144, 145; 144, 148; 145, comparison_operator:is; 145, 146; 145, 147; 146, identifier:data; 147, None; 148, block; 148, 149; 149, return_statement; 149, 150; 150, identifier:data; 151, if_statement; 151, 152; 151, 155; 151, 160; 152, comparison_operator:==; 152, 153; 152, 154; 153, identifier:limit; 154, integer:0; 155, block; 155, 156; 156, expression_statement; 156, 157; 157, assignment; 157, 158; 157, 159; 158, identifier:max_results_needed; 159, identifier:num_results_total; 160, else_clause; 160, 161; 161, block; 161, 162; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 165; 164, identifier:max_results_needed; 165, identifier:limit; 166, if_statement; 166, 167; 166, 172; 167, comparison_operator:>; 167, 168; 167, 169; 168, identifier:max_results_needed; 169, attribute; 169, 170; 169, 171; 170, identifier:self; 171, identifier:max_results_per_request; 172, block; 172, 173; 173, for_statement; 173, 174; 173, 175; 173, 186; 174, identifier:i; 175, call; 175, 176; 175, 177; 176, identifier:range; 177, argument_list; 177, 178; 177, 179; 178, integer:1; 179, binary_operator:+; 179, 180; 179, 185; 180, binary_operator://; 180, 181; 180, 182; 181, identifier:max_results_needed; 182, attribute; 182, 183; 182, 184; 183, identifier:self; 184, identifier:max_results_per_request; 185, integer:1; 186, block; 186, 187; 186, 195; 186, 213; 187, expression_statement; 187, 188; 188, assignment; 188, 189; 188, 190; 189, identifier:offset; 190, binary_operator:*; 190, 191; 190, 192; 191, identifier:i; 192, attribute; 192, 193; 192, 194; 193, identifier:self; 194, identifier:max_results_per_request; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 200; 197, pattern_list; 197, 198; 197, 199; 198, identifier:next_data; 199, identifier:_; 200, call; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:self; 203, identifier:__do_series_search; 204, argument_list; 204, 205; 205, binary_operator:+; 205, 206; 205, 209; 206, binary_operator:+; 206, 207; 206, 208; 207, identifier:url; 208, string:'&offset='; 209, call; 209, 210; 209, 211; 210, identifier:str; 211, argument_list; 211, 212; 212, identifier:offset; 213, expression_statement; 213, 214; 214, assignment; 214, 215; 214, 216; 215, identifier:data; 216, call; 216, 217; 216, 220; 217, attribute; 217, 218; 217, 219; 218, identifier:data; 219, identifier:append; 220, argument_list; 220, 221; 221, identifier:next_data; 222, return_statement; 222, 223; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:data; 226, identifier:head; 227, argument_list; 227, 228; 228, identifier:max_results_needed
def __get_search_results(self, url, limit, order_by, sort_order, filter): """ helper function for getting search results up to specified limit on the number of results. The Fred HTTP API truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data. """ order_by_options = ['search_rank', 'series_id', 'title', 'units', 'frequency', 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end', 'popularity'] if order_by is not None: if order_by in order_by_options: url = url + '&order_by=' + order_by else: raise ValueError('%s is not in the valid list of order_by options: %s' % (order_by, str(order_by_options))) if filter is not None: if len(filter) == 2: url = url + '&filter_variable=%s&filter_value=%s' % (filter[0], filter[1]) else: raise ValueError('Filter should be a 2 item tuple like (filter_variable, filter_value)') sort_order_options = ['asc', 'desc'] if sort_order is not None: if sort_order in sort_order_options: url = url + '&sort_order=' + sort_order else: raise ValueError('%s is not in the valid list of sort_order options: %s' % (sort_order, str(sort_order_options))) data, num_results_total = self.__do_series_search(url) if data is None: return data if limit == 0: max_results_needed = num_results_total else: max_results_needed = limit if max_results_needed > self.max_results_per_request: for i in range(1, max_results_needed // self.max_results_per_request + 1): offset = i * self.max_results_per_request next_data, _ = self.__do_series_search(url + '&offset=' + str(offset)) data = data.append(next_data) return data.head(max_results_needed)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 18; 2, function_name:search; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 4, identifier:self; 5, identifier:text; 6, default_parameter; 6, 7; 6, 8; 7, identifier:limit; 8, integer:1000; 9, default_parameter; 9, 10; 9, 11; 10, identifier:order_by; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:sort_order; 14, None; 15, default_parameter; 15, 16; 15, 17; 16, identifier:filter; 17, None; 18, block; 18, 19; 18, 21; 18, 34; 18, 47; 19, expression_statement; 19, 20; 20, comment; 21, expression_statement; 21, 22; 22, assignment; 22, 23; 22, 24; 23, identifier:url; 24, binary_operator:%; 24, 25; 24, 26; 25, string:"%s/series/search?search_text=%s&"; 26, tuple; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:self; 29, identifier:root_url; 30, call; 30, 31; 30, 32; 31, identifier:quote_plus; 32, argument_list; 32, 33; 33, identifier:text; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:info; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:self; 40, identifier:__get_search_results; 41, argument_list; 41, 42; 41, 43; 41, 44; 41, 45; 41, 46; 42, identifier:url; 43, identifier:limit; 44, identifier:order_by; 45, identifier:sort_order; 46, identifier:filter; 47, return_statement; 47, 48; 48, identifier:info
def search(self, text, limit=1000, order_by=None, sort_order=None, filter=None): """ Do a fulltext search for series in the Fred dataset. Returns information about matching series in a DataFrame. Parameters ---------- text : str text to do fulltext search on, e.g., 'Real GDP' limit : int, optional limit the number of results to this value. If limit is 0, it means fetching all results without limit. order_by : str, optional order the results by a criterion. Valid options are 'search_rank', 'series_id', 'title', 'units', 'frequency', 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end', 'popularity' sort_order : str, optional sort the results by ascending or descending order. Valid options are 'asc' or 'desc' filter : tuple, optional filters the results. Expects a tuple like (filter_variable, filter_value). Valid filter_variable values are 'frequency', 'units', and 'seasonal_adjustment' Returns ------- info : DataFrame a DataFrame containing information about the matching Fred series """ url = "%s/series/search?search_text=%s&" % (self.root_url, quote_plus(text)) info = self.__get_search_results(url, limit, order_by, sort_order, filter) return info
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 18; 2, function_name:search_by_release; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 4, identifier:self; 5, identifier:release_id; 6, default_parameter; 6, 7; 6, 8; 7, identifier:limit; 8, integer:0; 9, default_parameter; 9, 10; 9, 11; 10, identifier:order_by; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:sort_order; 14, None; 15, default_parameter; 15, 16; 15, 17; 16, identifier:filter; 17, None; 18, block; 18, 19; 18, 21; 18, 31; 18, 44; 18, 59; 19, expression_statement; 19, 20; 20, comment; 21, expression_statement; 21, 22; 22, assignment; 22, 23; 22, 24; 23, identifier:url; 24, binary_operator:%; 24, 25; 24, 26; 25, string:"%s/release/series?release_id=%d"; 26, tuple; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:self; 29, identifier:root_url; 30, identifier:release_id; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:info; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:self; 37, identifier:__get_search_results; 38, argument_list; 38, 39; 38, 40; 38, 41; 38, 42; 38, 43; 39, identifier:url; 40, identifier:limit; 41, identifier:order_by; 42, identifier:sort_order; 43, identifier:filter; 44, if_statement; 44, 45; 44, 48; 45, comparison_operator:is; 45, 46; 45, 47; 46, identifier:info; 47, None; 48, block; 48, 49; 49, raise_statement; 49, 50; 50, call; 50, 51; 50, 52; 51, identifier:ValueError; 52, argument_list; 52, 53; 53, binary_operator:+; 53, 54; 53, 55; 54, string:'No series exists for release id: '; 55, call; 55, 56; 55, 57; 56, identifier:str; 57, argument_list; 57, 58; 58, identifier:release_id; 59, return_statement; 59, 60; 60, identifier:info
def search_by_release(self, release_id, limit=0, order_by=None, sort_order=None, filter=None): """ Search for series that belongs to a release id. Returns information about matching series in a DataFrame. Parameters ---------- release_id : int release id, e.g., 151 limit : int, optional limit the number of results to this value. If limit is 0, it means fetching all results without limit. order_by : str, optional order the results by a criterion. Valid options are 'search_rank', 'series_id', 'title', 'units', 'frequency', 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end', 'popularity' sort_order : str, optional sort the results by ascending or descending order. Valid options are 'asc' or 'desc' filter : tuple, optional filters the results. Expects a tuple like (filter_variable, filter_value). Valid filter_variable values are 'frequency', 'units', and 'seasonal_adjustment' Returns ------- info : DataFrame a DataFrame containing information about the matching Fred series """ url = "%s/release/series?release_id=%d" % (self.root_url, release_id) info = self.__get_search_results(url, limit, order_by, sort_order, filter) if info is None: raise ValueError('No series exists for release id: ' + str(release_id)) return info
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 18; 2, function_name:search_by_category; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 4, identifier:self; 5, identifier:category_id; 6, default_parameter; 6, 7; 6, 8; 7, identifier:limit; 8, integer:0; 9, default_parameter; 9, 10; 9, 11; 10, identifier:order_by; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:sort_order; 14, None; 15, default_parameter; 15, 16; 15, 17; 16, identifier:filter; 17, None; 18, block; 18, 19; 18, 21; 18, 31; 18, 44; 18, 59; 19, expression_statement; 19, 20; 20, comment; 21, expression_statement; 21, 22; 22, assignment; 22, 23; 22, 24; 23, identifier:url; 24, binary_operator:%; 24, 25; 24, 26; 25, string:"%s/category/series?category_id=%d&"; 26, tuple; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:self; 29, identifier:root_url; 30, identifier:category_id; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:info; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:self; 37, identifier:__get_search_results; 38, argument_list; 38, 39; 38, 40; 38, 41; 38, 42; 38, 43; 39, identifier:url; 40, identifier:limit; 41, identifier:order_by; 42, identifier:sort_order; 43, identifier:filter; 44, if_statement; 44, 45; 44, 48; 45, comparison_operator:is; 45, 46; 45, 47; 46, identifier:info; 47, None; 48, block; 48, 49; 49, raise_statement; 49, 50; 50, call; 50, 51; 50, 52; 51, identifier:ValueError; 52, argument_list; 52, 53; 53, binary_operator:+; 53, 54; 53, 55; 54, string:'No series exists for category id: '; 55, call; 55, 56; 55, 57; 56, identifier:str; 57, argument_list; 57, 58; 58, identifier:category_id; 59, return_statement; 59, 60; 60, identifier:info
def search_by_category(self, category_id, limit=0, order_by=None, sort_order=None, filter=None): """ Search for series that belongs to a category id. Returns information about matching series in a DataFrame. Parameters ---------- category_id : int category id, e.g., 32145 limit : int, optional limit the number of results to this value. If limit is 0, it means fetching all results without limit. order_by : str, optional order the results by a criterion. Valid options are 'search_rank', 'series_id', 'title', 'units', 'frequency', 'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated', 'observation_start', 'observation_end', 'popularity' sort_order : str, optional sort the results by ascending or descending order. Valid options are 'asc' or 'desc' filter : tuple, optional filters the results. Expects a tuple like (filter_variable, filter_value). Valid filter_variable values are 'frequency', 'units', and 'seasonal_adjustment' Returns ------- info : DataFrame a DataFrame containing information about the matching Fred series """ url = "%s/category/series?category_id=%d&" % (self.root_url, category_id) info = self.__get_search_results(url, limit, order_by, sort_order, filter) if info is None: raise ValueError('No series exists for category id: ' + str(category_id)) return info
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:format_name; 3, parameters; 3, 4; 4, identifier:subject; 5, block; 5, 6; 5, 8; 5, 33; 6, expression_statement; 6, 7; 7, comment; 8, if_statement; 8, 9; 8, 16; 9, call; 9, 10; 9, 11; 10, identifier:isinstance; 11, argument_list; 11, 12; 11, 13; 12, identifier:subject; 13, attribute; 13, 14; 13, 15; 14, identifier:x509; 15, identifier:Name; 16, block; 16, 17; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:subject; 20, list_comprehension; 20, 21; 20, 30; 21, tuple; 21, 22; 21, 27; 22, subscript; 22, 23; 22, 24; 23, identifier:OID_NAME_MAPPINGS; 24, attribute; 24, 25; 24, 26; 25, identifier:s; 26, identifier:oid; 27, attribute; 27, 28; 27, 29; 28, identifier:s; 29, identifier:value; 30, for_in_clause; 30, 31; 30, 32; 31, identifier:s; 32, identifier:subject; 33, return_statement; 33, 34; 34, binary_operator:%; 34, 35; 34, 36; 35, string:'/%s'; 36, parenthesized_expression; 36, 37; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, string:'/'; 40, identifier:join; 41, argument_list; 41, 42; 42, list_comprehension; 42, 43; 42, 54; 43, binary_operator:%; 43, 44; 43, 45; 44, string:'%s=%s'; 45, tuple; 45, 46; 45, 50; 46, call; 46, 47; 46, 48; 47, identifier:force_text; 48, argument_list; 48, 49; 49, identifier:k; 50, call; 50, 51; 50, 52; 51, identifier:force_text; 52, argument_list; 52, 53; 53, identifier:v; 54, for_in_clause; 54, 55; 54, 58; 55, pattern_list; 55, 56; 55, 57; 56, identifier:k; 57, identifier:v; 58, identifier:subject
def format_name(subject): """Convert a subject into the canonical form for distinguished names. This function does not take care of sorting the subject in any meaningful order. Examples:: >>> format_name([('CN', 'example.com'), ]) '/CN=example.com' >>> format_name([('CN', 'example.com'), ('O', "My Organization"), ]) '/CN=example.com/O=My Organization' """ if isinstance(subject, x509.Name): subject = [(OID_NAME_MAPPINGS[s.oid], s.value) for s in subject] return '/%s' % ('/'.join(['%s=%s' % (force_text(k), force_text(v)) for k, v in subject]))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:parse_name; 3, parameters; 3, 4; 4, identifier:name; 5, block; 5, 6; 5, 8; 5, 16; 5, 23; 5, 70; 5, 71; 5, 109; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:name; 11, call; 11, 12; 11, 15; 12, attribute; 12, 13; 12, 14; 13, identifier:name; 14, identifier:strip; 15, argument_list; 16, if_statement; 16, 17; 16, 19; 16, 20; 17, not_operator; 17, 18; 18, identifier:name; 19, comment; 20, block; 20, 21; 21, return_statement; 21, 22; 22, list:[]; 23, try_statement; 23, 24; 23, 53; 24, block; 24, 25; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:items; 28, list_comprehension; 28, 29; 28, 45; 29, tuple; 29, 30; 29, 39; 30, subscript; 30, 31; 30, 32; 31, identifier:NAME_CASE_MAPPINGS; 32, call; 32, 33; 32, 38; 33, attribute; 33, 34; 33, 37; 34, subscript; 34, 35; 34, 36; 35, identifier:t; 36, integer:0; 37, identifier:upper; 38, argument_list; 39, call; 39, 40; 39, 41; 40, identifier:force_text; 41, argument_list; 41, 42; 42, subscript; 42, 43; 42, 44; 43, identifier:t; 44, integer:2; 45, for_in_clause; 45, 46; 45, 47; 46, identifier:t; 47, call; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:NAME_RE; 50, identifier:findall; 51, argument_list; 51, 52; 52, identifier:name; 53, except_clause; 53, 54; 53, 58; 54, as_pattern; 54, 55; 54, 56; 55, identifier:KeyError; 56, as_pattern_target; 56, 57; 57, identifier:e; 58, block; 58, 59; 59, raise_statement; 59, 60; 60, call; 60, 61; 60, 62; 61, identifier:ValueError; 62, argument_list; 62, 63; 63, binary_operator:%; 63, 64; 63, 65; 64, string:'Unknown x509 name field: %s'; 65, subscript; 65, 66; 65, 69; 66, attribute; 66, 67; 66, 68; 67, identifier:e; 68, identifier:args; 69, integer:0; 70, comment; 71, for_statement; 71, 72; 71, 75; 71, 80; 72, pattern_list; 72, 73; 72, 74; 73, identifier:key; 74, identifier:oid; 75, call; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:NAME_OID_MAPPINGS; 78, identifier:items; 79, argument_list; 80, block; 80, 81; 81, if_statement; 81, 82; 81, 101; 82, boolean_operator:and; 82, 83; 82, 98; 83, comparison_operator:>; 83, 84; 83, 97; 84, call; 84, 85; 84, 86; 85, identifier:sum; 86, generator_expression; 86, 87; 86, 88; 86, 91; 87, integer:1; 88, for_in_clause; 88, 89; 88, 90; 89, identifier:t; 90, identifier:items; 91, if_clause; 91, 92; 92, comparison_operator:==; 92, 93; 92, 96; 93, subscript; 93, 94; 93, 95; 94, identifier:t; 95, integer:0; 96, identifier:key; 97, integer:1; 98, comparison_operator:not; 98, 99; 98, 100; 99, identifier:oid; 100, identifier:MULTIPLE_OIDS; 101, block; 101, 102; 102, raise_statement; 102, 103; 103, call; 103, 104; 103, 105; 104, identifier:ValueError; 105, argument_list; 105, 106; 106, binary_operator:%; 106, 107; 106, 108; 107, string:'Subject contains multiple "%s" fields'; 108, identifier:key; 109, return_statement; 109, 110; 110, call; 110, 111; 110, 112; 111, identifier:sort_name; 112, argument_list; 112, 113; 113, identifier:items
def parse_name(name): """Parses a subject string as used in OpenSSLs command line utilities. The ``name`` is expected to be close to the subject format commonly used by OpenSSL, for example ``/C=AT/L=Vienna/CN=example.com/[email protected]``. The function does its best to be lenient on deviations from the format, object identifiers are case-insensitive (e.g. ``cn`` is the same as ``CN``, whitespace at the start and end is stripped and the subject does not have to start with a slash (``/``). >>> parse_name('/CN=example.com') [('CN', 'example.com')] >>> parse_name('c=AT/l= Vienna/o="ex org"/CN=example.com') [('C', 'AT'), ('L', 'Vienna'), ('O', 'ex org'), ('CN', 'example.com')] Dictionary keys are normalized to the values of :py:const:`OID_NAME_MAPPINGS` and keys will be sorted based on x509 name specifications regardless of the given order: >>> parse_name('L="Vienna / District"/[email protected]') [('L', 'Vienna / District'), ('emailAddress', '[email protected]')] >>> parse_name('/C=AT/CN=example.com') == parse_name('/CN=example.com/C=AT') True Due to the magic of :py:const:`NAME_RE`, the function even supports quoting strings and including slashes, so strings like ``/OU="Org / Org Unit"/CN=example.com`` will work as expected. >>> parse_name('L="Vienna / District"/CN=example.com') [('L', 'Vienna / District'), ('CN', 'example.com')] But note that it's still easy to trick this function, if you really want to. The following example is *not* a valid subject, the location is just bogus, and whatever you were expecting as output, it's certainly different: >>> parse_name('L="Vienna " District"/CN=example.com') [('L', 'Vienna'), ('CN', 'example.com')] Examples of where this string is used are: .. code-block:: console # openssl req -new -key priv.key -out csr -utf8 -batch -sha256 -subj '/C=AT/CN=example.com' # openssl x509 -in cert.pem -noout -subject -nameopt compat /C=AT/L=Vienna/CN=example.com """ name = name.strip() if not name: # empty subjects are ok return [] try: items = [(NAME_CASE_MAPPINGS[t[0].upper()], force_text(t[2])) for t in NAME_RE.findall(name)] except KeyError as e: raise ValueError('Unknown x509 name field: %s' % e.args[0]) # Check that no OIDs not in MULTIPLE_OIDS occur more then once for key, oid in NAME_OID_MAPPINGS.items(): if sum(1 for t in items if t[0] == key) > 1 and oid not in MULTIPLE_OIDS: raise ValueError('Subject contains multiple "%s" fields' % key) return sort_name(items)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:parse_general_name; 3, parameters; 3, 4; 4, identifier:name; 5, block; 5, 6; 5, 8; 5, 15; 5, 19; 5, 28; 5, 51; 5, 214; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:name; 11, call; 11, 12; 11, 13; 12, identifier:force_text; 13, argument_list; 13, 14; 14, identifier:name; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:typ; 18, None; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:match; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:GENERAL_NAME_RE; 25, identifier:match; 26, argument_list; 26, 27; 27, identifier:name; 28, if_statement; 28, 29; 28, 32; 29, comparison_operator:is; 29, 30; 29, 31; 30, identifier:match; 31, None; 32, block; 32, 33; 32, 43; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 38; 35, pattern_list; 35, 36; 35, 37; 36, identifier:typ; 37, identifier:name; 38, call; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:match; 41, identifier:groups; 42, argument_list; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 46; 45, identifier:typ; 46, call; 46, 47; 46, 50; 47, attribute; 47, 48; 47, 49; 48, identifier:typ; 49, identifier:lower; 50, argument_list; 51, if_statement; 51, 52; 51, 55; 52, comparison_operator:is; 52, 53; 52, 54; 53, identifier:typ; 54, None; 55, block; 55, 56; 55, 80; 55, 102; 55, 125; 55, 126; 55, 142; 55, 158; 55, 159; 55, 206; 55, 207; 56, if_statement; 56, 57; 56, 64; 56, 65; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:re; 60, identifier:match; 61, argument_list; 61, 62; 61, 63; 62, string:'[a-z0-9]{2,}://'; 63, identifier:name; 64, comment; 65, block; 65, 66; 66, try_statement; 66, 67; 66, 75; 67, block; 67, 68; 68, return_statement; 68, 69; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:x509; 72, identifier:UniformResourceIdentifier; 73, argument_list; 73, 74; 74, identifier:name; 75, except_clause; 75, 76; 75, 77; 75, 78; 76, identifier:Exception; 77, comment; 78, block; 78, 79; 79, pass_statement; 80, if_statement; 80, 81; 80, 84; 80, 85; 81, comparison_operator:in; 81, 82; 81, 83; 82, string:'@'; 83, identifier:name; 84, comment; 85, block; 85, 86; 86, try_statement; 86, 87; 86, 98; 87, block; 87, 88; 88, return_statement; 88, 89; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:x509; 92, identifier:RFC822Name; 93, argument_list; 93, 94; 94, call; 94, 95; 94, 96; 95, identifier:validate_email; 96, argument_list; 96, 97; 97, identifier:name; 98, except_clause; 98, 99; 98, 100; 99, identifier:Exception; 100, block; 100, 101; 101, pass_statement; 102, if_statement; 102, 103; 102, 113; 102, 114; 103, call; 103, 104; 103, 111; 104, attribute; 104, 105; 104, 110; 105, call; 105, 106; 105, 109; 106, attribute; 106, 107; 106, 108; 107, identifier:name; 108, identifier:strip; 109, argument_list; 110, identifier:startswith; 111, argument_list; 111, 112; 112, string:'/'; 113, comment; 114, block; 114, 115; 115, return_statement; 115, 116; 116, call; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:x509; 119, identifier:DirectoryName; 120, argument_list; 120, 121; 121, call; 121, 122; 121, 123; 122, identifier:x509_name; 123, argument_list; 123, 124; 124, identifier:name; 125, comment; 126, try_statement; 126, 127; 126, 138; 127, block; 127, 128; 128, return_statement; 128, 129; 129, call; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:x509; 132, identifier:IPAddress; 133, argument_list; 133, 134; 134, call; 134, 135; 134, 136; 135, identifier:ip_address; 136, argument_list; 136, 137; 137, identifier:name; 138, except_clause; 138, 139; 138, 140; 139, identifier:ValueError; 140, block; 140, 141; 141, pass_statement; 142, try_statement; 142, 143; 142, 154; 143, block; 143, 144; 144, return_statement; 144, 145; 145, call; 145, 146; 145, 149; 146, attribute; 146, 147; 146, 148; 147, identifier:x509; 148, identifier:IPAddress; 149, argument_list; 149, 150; 150, call; 150, 151; 150, 152; 151, identifier:ip_network; 152, argument_list; 152, 153; 153, identifier:name; 154, except_clause; 154, 155; 154, 156; 155, identifier:ValueError; 156, block; 156, 157; 157, pass_statement; 158, comment; 159, if_statement; 159, 160; 159, 166; 159, 178; 159, 197; 160, call; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:name; 163, identifier:startswith; 164, argument_list; 164, 165; 165, string:'*.'; 166, block; 166, 167; 167, expression_statement; 167, 168; 168, call; 168, 169; 168, 172; 169, attribute; 169, 170; 169, 171; 170, identifier:idna; 171, identifier:encode; 172, argument_list; 172, 173; 173, subscript; 173, 174; 173, 175; 174, identifier:name; 175, slice; 175, 176; 175, 177; 176, integer:2; 177, colon; 178, elif_clause; 178, 179; 178, 185; 179, call; 179, 180; 179, 183; 180, attribute; 180, 181; 180, 182; 181, identifier:name; 182, identifier:startswith; 183, argument_list; 183, 184; 184, string:'.'; 185, block; 185, 186; 186, expression_statement; 186, 187; 187, call; 187, 188; 187, 191; 188, attribute; 188, 189; 188, 190; 189, identifier:idna; 190, identifier:encode; 191, argument_list; 191, 192; 192, subscript; 192, 193; 192, 194; 193, identifier:name; 194, slice; 194, 195; 194, 196; 195, integer:1; 196, colon; 197, else_clause; 197, 198; 198, block; 198, 199; 199, expression_statement; 199, 200; 200, call; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:idna; 203, identifier:encode; 204, argument_list; 204, 205; 205, identifier:name; 206, comment; 207, return_statement; 207, 208; 208, call; 208, 209; 208, 212; 209, attribute; 209, 210; 209, 211; 210, identifier:x509; 211, identifier:DNSName; 212, argument_list; 212, 213; 213, identifier:name; 214, if_statement; 214, 215; 214, 218; 214, 226; 214, 241; 214, 283; 214, 300; 214, 421; 214, 436; 215, comparison_operator:==; 215, 216; 215, 217; 216, identifier:typ; 217, string:'uri'; 218, block; 218, 219; 219, return_statement; 219, 220; 220, call; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:x509; 223, identifier:UniformResourceIdentifier; 224, argument_list; 224, 225; 225, identifier:name; 226, elif_clause; 226, 227; 226, 230; 227, comparison_operator:==; 227, 228; 227, 229; 228, identifier:typ; 229, string:'email'; 230, block; 230, 231; 231, return_statement; 231, 232; 232, call; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:x509; 235, identifier:RFC822Name; 236, argument_list; 236, 237; 237, call; 237, 238; 237, 239; 238, identifier:validate_email; 239, argument_list; 239, 240; 240, identifier:name; 241, elif_clause; 241, 242; 241, 245; 242, comparison_operator:==; 242, 243; 242, 244; 243, identifier:typ; 244, string:'ip'; 245, block; 245, 246; 245, 262; 245, 278; 246, try_statement; 246, 247; 246, 258; 247, block; 247, 248; 248, return_statement; 248, 249; 249, call; 249, 250; 249, 253; 250, attribute; 250, 251; 250, 252; 251, identifier:x509; 252, identifier:IPAddress; 253, argument_list; 253, 254; 254, call; 254, 255; 254, 256; 255, identifier:ip_address; 256, argument_list; 256, 257; 257, identifier:name; 258, except_clause; 258, 259; 258, 260; 259, identifier:ValueError; 260, block; 260, 261; 261, pass_statement; 262, try_statement; 262, 263; 262, 274; 263, block; 263, 264; 264, return_statement; 264, 265; 265, call; 265, 266; 265, 269; 266, attribute; 266, 267; 266, 268; 267, identifier:x509; 268, identifier:IPAddress; 269, argument_list; 269, 270; 270, call; 270, 271; 270, 272; 271, identifier:ip_network; 272, argument_list; 272, 273; 273, identifier:name; 274, except_clause; 274, 275; 274, 276; 275, identifier:ValueError; 276, block; 276, 277; 277, pass_statement; 278, raise_statement; 278, 279; 279, call; 279, 280; 279, 281; 280, identifier:ValueError; 281, argument_list; 281, 282; 282, string:'Could not parse IP address.'; 283, elif_clause; 283, 284; 283, 287; 284, comparison_operator:==; 284, 285; 284, 286; 285, identifier:typ; 286, string:'rid'; 287, block; 287, 288; 288, return_statement; 288, 289; 289, call; 289, 290; 289, 293; 290, attribute; 290, 291; 290, 292; 291, identifier:x509; 292, identifier:RegisteredID; 293, argument_list; 293, 294; 294, call; 294, 295; 294, 298; 295, attribute; 295, 296; 295, 297; 296, identifier:x509; 297, identifier:ObjectIdentifier; 298, argument_list; 298, 299; 299, identifier:name; 300, elif_clause; 300, 301; 300, 304; 301, comparison_operator:==; 301, 302; 301, 303; 302, identifier:typ; 303, string:'othername'; 304, block; 304, 305; 304, 309; 305, expression_statement; 305, 306; 306, assignment; 306, 307; 306, 308; 307, identifier:regex; 308, string:"(.*);(.*):(.*)"; 309, if_statement; 309, 310; 309, 319; 309, 412; 310, comparison_operator:is; 310, 311; 310, 318; 311, call; 311, 312; 311, 315; 312, attribute; 312, 313; 312, 314; 313, identifier:re; 314, identifier:match; 315, argument_list; 315, 316; 315, 317; 316, identifier:regex; 317, identifier:name; 318, None; 319, block; 319, 320; 319, 337; 319, 346; 319, 397; 319, 404; 320, expression_statement; 320, 321; 321, assignment; 321, 322; 321, 326; 322, pattern_list; 322, 323; 322, 324; 322, 325; 323, identifier:oid; 324, identifier:asn_typ; 325, identifier:val; 326, call; 326, 327; 326, 336; 327, attribute; 327, 328; 327, 335; 328, call; 328, 329; 328, 332; 329, attribute; 329, 330; 329, 331; 330, identifier:re; 331, identifier:match; 332, argument_list; 332, 333; 332, 334; 333, identifier:regex; 334, identifier:name; 335, identifier:groups; 336, argument_list; 337, expression_statement; 337, 338; 338, assignment; 338, 339; 338, 340; 339, identifier:oid; 340, call; 340, 341; 340, 344; 341, attribute; 341, 342; 341, 343; 342, identifier:x509; 343, identifier:ObjectIdentifier; 344, argument_list; 344, 345; 345, identifier:oid; 346, if_statement; 346, 347; 346, 350; 346, 360; 346, 388; 347, comparison_operator:==; 347, 348; 347, 349; 348, identifier:asn_typ; 349, string:'UTF8'; 350, block; 350, 351; 351, expression_statement; 351, 352; 352, assignment; 352, 353; 352, 354; 353, identifier:val; 354, call; 354, 355; 354, 358; 355, attribute; 355, 356; 355, 357; 356, identifier:val; 357, identifier:encode; 358, argument_list; 358, 359; 359, string:'utf-8'; 360, elif_clause; 360, 361; 360, 364; 361, comparison_operator:==; 361, 362; 361, 363; 362, identifier:asn_typ; 363, string:'OctetString'; 364, block; 364, 365; 364, 377; 365, expression_statement; 365, 366; 366, assignment; 366, 367; 366, 368; 367, identifier:val; 368, call; 368, 369; 368, 370; 369, identifier:bytes; 370, argument_list; 370, 371; 371, call; 371, 372; 371, 375; 372, attribute; 372, 373; 372, 374; 373, identifier:bytearray; 374, identifier:fromhex; 375, argument_list; 375, 376; 376, identifier:val; 377, expression_statement; 377, 378; 378, assignment; 378, 379; 378, 380; 379, identifier:val; 380, call; 380, 381; 380, 387; 381, attribute; 381, 382; 381, 386; 382, call; 382, 383; 382, 384; 383, identifier:OctetString; 384, argument_list; 384, 385; 385, identifier:val; 386, identifier:dump; 387, argument_list; 388, else_clause; 388, 389; 389, block; 389, 390; 390, raise_statement; 390, 391; 391, call; 391, 392; 391, 393; 392, identifier:ValueError; 393, argument_list; 393, 394; 394, binary_operator:%; 394, 395; 394, 396; 395, string:'Unsupported ASN type in otherName: %s'; 396, identifier:asn_typ; 397, expression_statement; 397, 398; 398, assignment; 398, 399; 398, 400; 399, identifier:val; 400, call; 400, 401; 400, 402; 401, identifier:force_bytes; 402, argument_list; 402, 403; 403, identifier:val; 404, return_statement; 404, 405; 405, call; 405, 406; 405, 409; 406, attribute; 406, 407; 406, 408; 407, identifier:x509; 408, identifier:OtherName; 409, argument_list; 409, 410; 409, 411; 410, identifier:oid; 411, identifier:val; 412, else_clause; 412, 413; 413, block; 413, 414; 414, raise_statement; 414, 415; 415, call; 415, 416; 415, 417; 416, identifier:ValueError; 417, argument_list; 417, 418; 418, binary_operator:%; 418, 419; 418, 420; 419, string:'Incorrect otherName format: %s'; 420, identifier:name; 421, elif_clause; 421, 422; 421, 425; 422, comparison_operator:==; 422, 423; 422, 424; 423, identifier:typ; 424, string:'dirname'; 425, block; 425, 426; 426, return_statement; 426, 427; 427, call; 427, 428; 427, 431; 428, attribute; 428, 429; 428, 430; 429, identifier:x509; 430, identifier:DirectoryName; 431, argument_list; 431, 432; 432, call; 432, 433; 432, 434; 433, identifier:x509_name; 434, argument_list; 434, 435; 435, identifier:name; 436, else_clause; 436, 437; 436, 438; 436, 439; 437, comment; 438, comment; 439, block; 439, 440; 439, 487; 440, if_statement; 440, 441; 440, 447; 440, 459; 440, 478; 441, call; 441, 442; 441, 445; 442, attribute; 442, 443; 442, 444; 443, identifier:name; 444, identifier:startswith; 445, argument_list; 445, 446; 446, string:'*.'; 447, block; 447, 448; 448, expression_statement; 448, 449; 449, call; 449, 450; 449, 453; 450, attribute; 450, 451; 450, 452; 451, identifier:idna; 452, identifier:encode; 453, argument_list; 453, 454; 454, subscript; 454, 455; 454, 456; 455, identifier:name; 456, slice; 456, 457; 456, 458; 457, integer:2; 458, colon; 459, elif_clause; 459, 460; 459, 466; 460, call; 460, 461; 460, 464; 461, attribute; 461, 462; 461, 463; 462, identifier:name; 463, identifier:startswith; 464, argument_list; 464, 465; 465, string:'.'; 466, block; 466, 467; 467, expression_statement; 467, 468; 468, call; 468, 469; 468, 472; 469, attribute; 469, 470; 469, 471; 470, identifier:idna; 471, identifier:encode; 472, argument_list; 472, 473; 473, subscript; 473, 474; 473, 475; 474, identifier:name; 475, slice; 475, 476; 475, 477; 476, integer:1; 477, colon; 478, else_clause; 478, 479; 479, block; 479, 480; 480, expression_statement; 480, 481; 481, call; 481, 482; 481, 485; 482, attribute; 482, 483; 482, 484; 483, identifier:idna; 484, identifier:encode; 485, argument_list; 485, 486; 486, identifier:name; 487, return_statement; 487, 488; 488, call; 488, 489; 488, 492; 489, attribute; 489, 490; 489, 491; 490, identifier:x509; 491, identifier:DNSName; 492, argument_list; 492, 493; 493, identifier:name
def parse_general_name(name): """Parse a general name from user input. This function will do its best to detect the intended type of any value passed to it: >>> parse_general_name('example.com') <DNSName(value='example.com')> >>> parse_general_name('*.example.com') <DNSName(value='*.example.com')> >>> parse_general_name('.example.com') # Syntax used e.g. for NameConstraints: All levels of subdomains <DNSName(value='.example.com')> >>> parse_general_name('[email protected]') <RFC822Name(value='[email protected]')> >>> parse_general_name('https://example.com') <UniformResourceIdentifier(value='https://example.com')> >>> parse_general_name('1.2.3.4') <IPAddress(value=1.2.3.4)> >>> parse_general_name('fd00::1') <IPAddress(value=fd00::1)> >>> parse_general_name('/CN=example.com') <DirectoryName(value=<Name(CN=example.com)>)> The default fallback is to assume a :py:class:`~cg:cryptography.x509.DNSName`. If this doesn't work, an exception will be raised: >>> parse_general_name('foo..bar`*123') # doctest: +ELLIPSIS Traceback (most recent call last): ... idna.core.IDNAError: ... If you want to override detection, you can prefix the name to match :py:const:`GENERAL_NAME_RE`: >>> parse_general_name('email:[email protected]') <RFC822Name(value='[email protected]')> >>> parse_general_name('URI:https://example.com') <UniformResourceIdentifier(value='https://example.com')> >>> parse_general_name('dirname:/CN=example.com') <DirectoryName(value=<Name(CN=example.com)>)> Some more exotic values can only be generated by using this prefix: >>> parse_general_name('rid:2.5.4.3') <RegisteredID(value=<ObjectIdentifier(oid=2.5.4.3, name=commonName)>)> >>> parse_general_name('otherName:2.5.4.3;UTF8:example.com') <OtherName(type_id=<ObjectIdentifier(oid=2.5.4.3, name=commonName)>, value=b'example.com')> If you give a prefixed value, this function is less forgiving of any typos and does not catch any exceptions: >>> parse_general_name('email:foo@bar com') Traceback (most recent call last): ... ValueError: Invalid domain: bar com """ name = force_text(name) typ = None match = GENERAL_NAME_RE.match(name) if match is not None: typ, name = match.groups() typ = typ.lower() if typ is None: if re.match('[a-z0-9]{2,}://', name): # Looks like a URI try: return x509.UniformResourceIdentifier(name) except Exception: # pragma: no cover - this really accepts anything pass if '@' in name: # Looks like an Email address try: return x509.RFC822Name(validate_email(name)) except Exception: pass if name.strip().startswith('/'): # maybe it's a dirname? return x509.DirectoryName(x509_name(name)) # Try to parse this as IPAddress/Network try: return x509.IPAddress(ip_address(name)) except ValueError: pass try: return x509.IPAddress(ip_network(name)) except ValueError: pass # Try to encode as domain name. DNSName() does not validate the domain name, but this check will fail. if name.startswith('*.'): idna.encode(name[2:]) elif name.startswith('.'): idna.encode(name[1:]) else: idna.encode(name) # Almost anything passes as DNS name, so this is our default fallback return x509.DNSName(name) if typ == 'uri': return x509.UniformResourceIdentifier(name) elif typ == 'email': return x509.RFC822Name(validate_email(name)) elif typ == 'ip': try: return x509.IPAddress(ip_address(name)) except ValueError: pass try: return x509.IPAddress(ip_network(name)) except ValueError: pass raise ValueError('Could not parse IP address.') elif typ == 'rid': return x509.RegisteredID(x509.ObjectIdentifier(name)) elif typ == 'othername': regex = "(.*);(.*):(.*)" if re.match(regex, name) is not None: oid, asn_typ, val = re.match(regex, name).groups() oid = x509.ObjectIdentifier(oid) if asn_typ == 'UTF8': val = val.encode('utf-8') elif asn_typ == 'OctetString': val = bytes(bytearray.fromhex(val)) val = OctetString(val).dump() else: raise ValueError('Unsupported ASN type in otherName: %s' % asn_typ) val = force_bytes(val) return x509.OtherName(oid, val) else: raise ValueError('Incorrect otherName format: %s' % name) elif typ == 'dirname': return x509.DirectoryName(x509_name(name)) else: # Try to encode the domain name. DNSName() does not validate the domain name, but this # check will fail. if name.startswith('*.'): idna.encode(name[2:]) elif name.startswith('.'): idna.encode(name[1:]) else: idna.encode(name) return x509.DNSName(name)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:render; 3, parameters; 3, 4; 3, 5; 3, 7; 4, identifier:self; 5, list_splat_pattern; 5, 6; 6, identifier:args; 7, dictionary_splat_pattern; 7, 8; 8, identifier:kwargs; 9, block; 9, 10; 9, 12; 9, 13; 9, 14; 9, 24; 9, 39; 9, 63; 9, 79; 9, 80; 9, 81; 9, 94; 9, 100; 9, 138; 9, 153; 9, 154; 9, 188; 9, 198; 9, 207; 10, expression_statement; 10, 11; 11, comment; 12, comment; 13, comment; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:pretty; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:kwargs; 20, identifier:pop; 21, argument_list; 21, 22; 21, 23; 22, string:"pretty"; 23, False; 24, if_statement; 24, 25; 24, 32; 25, boolean_operator:and; 25, 26; 25, 27; 26, identifier:pretty; 27, comparison_operator:!=; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:self; 30, identifier:_stable; 31, string:"pretty"; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:self; 37, identifier:_stable; 38, False; 39, for_statement; 39, 40; 39, 41; 39, 42; 40, identifier:arg; 41, identifier:args; 42, block; 42, 43; 42, 49; 43, expression_statement; 43, 44; 44, assignment; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:self; 47, identifier:_stable; 48, False; 49, if_statement; 49, 50; 49, 55; 50, call; 50, 51; 50, 52; 51, identifier:isinstance; 52, argument_list; 52, 53; 52, 54; 53, identifier:arg; 54, identifier:dict; 55, block; 55, 56; 56, expression_statement; 56, 57; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:self; 60, identifier:inject; 61, argument_list; 61, 62; 62, identifier:arg; 63, if_statement; 63, 64; 63, 65; 64, identifier:kwargs; 65, block; 65, 66; 65, 72; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:self; 70, identifier:_stable; 71, False; 72, expression_statement; 72, 73; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:self; 76, identifier:inject; 77, argument_list; 77, 78; 78, identifier:kwargs; 79, comment; 80, comment; 81, if_statement; 81, 82; 81, 89; 82, boolean_operator:and; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:self; 85, identifier:_stable; 86, attribute; 86, 87; 86, 88; 87, identifier:self; 88, identifier:_render; 89, block; 89, 90; 90, return_statement; 90, 91; 91, attribute; 91, 92; 91, 93; 92, identifier:self; 93, identifier:_render; 94, expression_statement; 94, 95; 95, assignment; 95, 96; 95, 97; 96, identifier:pretty_pre; 97, assignment; 97, 98; 97, 99; 98, identifier:pretty_inner; 99, string:""; 100, if_statement; 100, 101; 100, 102; 101, identifier:pretty; 102, block; 102, 103; 102, 117; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:pretty_pre; 106, conditional_expression:if; 106, 107; 106, 115; 106, 116; 107, binary_operator:+; 107, 108; 107, 109; 108, string:"\n"; 109, parenthesized_expression; 109, 110; 110, binary_operator:*; 110, 111; 110, 112; 111, string:"\t"; 112, attribute; 112, 113; 112, 114; 113, identifier:self; 114, identifier:_depth; 115, identifier:pretty; 116, string:""; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:pretty_inner; 120, conditional_expression:if; 120, 121; 120, 129; 120, 137; 121, binary_operator:+; 121, 122; 121, 123; 122, string:"\n"; 123, parenthesized_expression; 123, 124; 124, binary_operator:*; 124, 125; 124, 126; 125, string:"\t"; 126, attribute; 126, 127; 126, 128; 127, identifier:self; 128, identifier:_depth; 129, comparison_operator:>; 129, 130; 129, 136; 130, call; 130, 131; 130, 132; 131, identifier:len; 132, argument_list; 132, 133; 133, attribute; 133, 134; 133, 135; 134, identifier:self; 135, identifier:childs; 136, integer:1; 137, string:""; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:inner; 141, conditional_expression:if; 141, 142; 141, 148; 141, 152; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:self; 145, identifier:render_childs; 146, argument_list; 146, 147; 147, identifier:pretty; 148, not_operator; 148, 149; 149, attribute; 149, 150; 149, 151; 150, identifier:self; 151, identifier:_void; 152, string:""; 153, comment; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 157; 156, identifier:tag_data; 157, subscript; 157, 158; 157, 177; 158, tuple; 158, 159; 158, 160; 158, 165; 158, 170; 158, 171; 158, 172; 159, identifier:pretty_pre; 160, call; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:self; 163, identifier:_get__tag; 164, argument_list; 165, call; 165, 166; 165, 169; 166, attribute; 166, 167; 166, 168; 167, identifier:self; 168, identifier:render_attrs; 169, argument_list; 170, identifier:inner; 171, identifier:pretty_inner; 172, call; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, identifier:self; 175, identifier:_get__tag; 176, argument_list; 177, slice; 177, 178; 177, 179; 178, colon; 179, binary_operator:-; 179, 180; 179, 181; 180, integer:6; 181, subscript; 181, 182; 181, 185; 182, list:[0, 3]; 182, 183; 182, 184; 183, integer:0; 184, integer:3; 185, attribute; 185, 186; 185, 187; 186, identifier:self; 187, identifier:_void; 188, expression_statement; 188, 189; 189, assignment; 189, 190; 189, 193; 190, attribute; 190, 191; 190, 192; 191, identifier:self; 192, identifier:_render; 193, binary_operator:%; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:self; 196, identifier:_template; 197, identifier:tag_data; 198, expression_statement; 198, 199; 199, assignment; 199, 200; 199, 203; 200, attribute; 200, 201; 200, 202; 201, identifier:self; 202, identifier:_stable; 203, conditional_expression:if; 203, 204; 203, 205; 203, 206; 204, string:"pretty"; 205, identifier:pretty; 206, True; 207, return_statement; 207, 208; 208, attribute; 208, 209; 208, 210; 209, identifier:self; 210, identifier:_render
def render(self, *args, **kwargs): """Renders the element and all his childrens.""" # args kwargs API provided for last minute content injection # self._reverse_mro_func('pre_render') pretty = kwargs.pop("pretty", False) if pretty and self._stable != "pretty": self._stable = False for arg in args: self._stable = False if isinstance(arg, dict): self.inject(arg) if kwargs: self._stable = False self.inject(kwargs) # If the tag or his contents are not changed and we already have rendered it # with the same attrs we skip all the work if self._stable and self._render: return self._render pretty_pre = pretty_inner = "" if pretty: pretty_pre = "\n" + ("\t" * self._depth) if pretty else "" pretty_inner = "\n" + ("\t" * self._depth) if len(self.childs) > 1 else "" inner = self.render_childs(pretty) if not self._void else "" # We declare the tag is stable and have an official render: tag_data = ( pretty_pre, self._get__tag(), self.render_attrs(), inner, pretty_inner, self._get__tag() )[: 6 - [0, 3][self._void]] self._render = self._template % tag_data self._stable = "pretty" if pretty else True return self._render
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 15; 2, function_name:_insert; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 4, identifier:self; 5, identifier:dom_group; 6, default_parameter; 6, 7; 6, 8; 7, identifier:idx; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:prepend; 11, False; 12, default_parameter; 12, 13; 12, 14; 13, identifier:name; 14, None; 15, block; 15, 16; 15, 18; 15, 29; 15, 52; 16, expression_statement; 16, 17; 17, comment; 18, if_statement; 18, 19; 18, 24; 19, boolean_operator:and; 19, 20; 19, 21; 20, identifier:idx; 21, comparison_operator:<; 21, 22; 21, 23; 22, identifier:idx; 23, integer:0; 24, block; 24, 25; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:idx; 28, integer:0; 29, if_statement; 29, 30; 29, 31; 29, 36; 30, identifier:prepend; 31, block; 31, 32; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:idx; 35, integer:0; 36, else_clause; 36, 37; 37, block; 37, 38; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 41; 40, identifier:idx; 41, conditional_expression:if; 41, 42; 41, 43; 41, 46; 42, identifier:idx; 43, comparison_operator:is; 43, 44; 43, 45; 44, identifier:idx; 45, None; 46, call; 46, 47; 46, 48; 47, identifier:len; 48, argument_list; 48, 49; 49, attribute; 49, 50; 49, 51; 50, identifier:self; 51, identifier:childs; 52, if_statement; 52, 53; 52, 56; 53, comparison_operator:is; 53, 54; 53, 55; 54, identifier:dom_group; 55, None; 56, block; 56, 57; 56, 78; 57, if_statement; 57, 58; 57, 72; 58, boolean_operator:or; 58, 59; 58, 65; 59, not_operator; 59, 60; 60, call; 60, 61; 60, 62; 61, identifier:isinstance; 62, argument_list; 62, 63; 62, 64; 63, identifier:dom_group; 64, identifier:Iterable; 65, call; 65, 66; 65, 67; 66, identifier:isinstance; 67, argument_list; 67, 68; 67, 69; 68, identifier:dom_group; 69, tuple; 69, 70; 69, 71; 70, identifier:DOMElement; 71, identifier:str; 72, block; 72, 73; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:dom_group; 76, list:[dom_group]; 76, 77; 77, identifier:dom_group; 78, for_statement; 78, 79; 78, 82; 78, 86; 79, pattern_list; 79, 80; 79, 81; 80, identifier:i_group; 81, identifier:elem; 82, call; 82, 83; 82, 84; 83, identifier:enumerate; 84, argument_list; 84, 85; 85, identifier:dom_group; 86, block; 86, 87; 87, if_statement; 87, 88; 87, 91; 87, 92; 88, comparison_operator:is; 88, 89; 88, 90; 89, identifier:elem; 90, None; 91, comment; 92, block; 92, 93; 92, 105; 92, 106; 92, 121; 93, expression_statement; 93, 94; 94, call; 94, 95; 94, 100; 95, attribute; 95, 96; 95, 99; 96, attribute; 96, 97; 96, 98; 97, identifier:self; 98, identifier:childs; 99, identifier:insert; 100, argument_list; 100, 101; 100, 104; 101, binary_operator:+; 101, 102; 101, 103; 102, identifier:idx; 103, identifier:i_group; 104, identifier:elem; 105, comment; 106, if_statement; 106, 107; 106, 114; 107, call; 107, 108; 107, 109; 108, identifier:issubclass; 109, argument_list; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:elem; 112, identifier:__class__; 113, identifier:DOMElement; 114, block; 114, 115; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:elem; 119, identifier:parent; 120, identifier:self; 121, if_statement; 121, 122; 121, 123; 122, identifier:name; 123, block; 123, 124; 124, expression_statement; 124, 125; 125, call; 125, 126; 125, 127; 126, identifier:setattr; 127, argument_list; 127, 128; 127, 129; 127, 130; 128, identifier:self; 129, identifier:name; 130, identifier:elem
def _insert(self, dom_group, idx=None, prepend=False, name=None): """Inserts a DOMGroup inside this element. If provided at the given index, if prepend at the start of the childs list, by default at the end. If the child is a DOMElement, correctly links the child. If the DOMGroup have a name, an attribute containing the child is created in this instance. """ if idx and idx < 0: idx = 0 if prepend: idx = 0 else: idx = idx if idx is not None else len(self.childs) if dom_group is not None: if not isinstance(dom_group, Iterable) or isinstance( dom_group, (DOMElement, str) ): dom_group = [dom_group] for i_group, elem in enumerate(dom_group): if elem is not None: # Element insertion in this DOMElement childs self.childs.insert(idx + i_group, elem) # Managing child attributes if needed if issubclass(elem.__class__, DOMElement): elem.parent = self if name: setattr(self, name, elem)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:check_label; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:labels; 5, identifier:required; 6, identifier:value_regex; 7, identifier:target_labels; 8, block; 8, 9; 8, 11; 8, 31; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:present; 14, boolean_operator:and; 14, 15; 14, 18; 15, comparison_operator:is; 15, 16; 15, 17; 16, identifier:target_labels; 17, None; 18, not_operator; 18, 19; 19, call; 19, 20; 19, 26; 20, attribute; 20, 21; 20, 25; 21, call; 21, 22; 21, 23; 22, identifier:set; 23, argument_list; 23, 24; 24, identifier:labels; 25, identifier:isdisjoint; 26, argument_list; 26, 27; 27, call; 27, 28; 27, 29; 28, identifier:set; 29, argument_list; 29, 30; 30, identifier:target_labels; 31, if_statement; 31, 32; 31, 33; 31, 92; 32, identifier:present; 33, block; 33, 34; 34, if_statement; 34, 35; 34, 39; 34, 42; 34, 88; 35, boolean_operator:and; 35, 36; 35, 37; 36, identifier:required; 37, not_operator; 37, 38; 38, identifier:value_regex; 39, block; 39, 40; 40, return_statement; 40, 41; 41, True; 42, elif_clause; 42, 43; 42, 44; 43, identifier:value_regex; 44, block; 44, 45; 44, 54; 44, 66; 44, 86; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:pattern; 48, call; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:re; 51, identifier:compile; 52, argument_list; 52, 53; 53, identifier:value_regex; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:present_labels; 57, binary_operator:&; 57, 58; 57, 62; 58, call; 58, 59; 58, 60; 59, identifier:set; 60, argument_list; 60, 61; 61, identifier:labels; 62, call; 62, 63; 62, 64; 63, identifier:set; 64, argument_list; 64, 65; 65, identifier:target_labels; 66, for_statement; 66, 67; 66, 68; 66, 69; 67, identifier:l; 68, identifier:present_labels; 69, block; 69, 70; 70, if_statement; 70, 71; 70, 83; 71, not_operator; 71, 72; 72, call; 72, 73; 72, 74; 73, identifier:bool; 74, argument_list; 74, 75; 75, call; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:pattern; 78, identifier:search; 79, argument_list; 79, 80; 80, subscript; 80, 81; 80, 82; 81, identifier:target_labels; 82, identifier:l; 83, block; 83, 84; 84, return_statement; 84, 85; 85, False; 86, return_statement; 86, 87; 87, True; 88, else_clause; 88, 89; 89, block; 89, 90; 90, return_statement; 90, 91; 91, False; 92, else_clause; 92, 93; 93, block; 93, 94; 94, return_statement; 94, 95; 95, not_operator; 95, 96; 96, identifier:required
def check_label(labels, required, value_regex, target_labels): """ Check if the label is required and match the regex :param labels: [str] :param required: bool (if the presence means pass or not) :param value_regex: str (using search method) :param target_labels: [str] :return: bool (required==True: True if the label is present and match the regex if specified) (required==False: True if the label is not present) """ present = target_labels is not None and not set(labels).isdisjoint(set(target_labels)) if present: if required and not value_regex: return True elif value_regex: pattern = re.compile(value_regex) present_labels = set(labels) & set(target_labels) for l in present_labels: if not bool(pattern.search(target_labels[l])): return False return True else: return False else: return not required
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:receive_fmf_metadata; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:name; 5, identifier:path; 6, default_parameter; 6, 7; 6, 8; 7, identifier:object_list; 8, False; 9, block; 9, 10; 9, 12; 9, 16; 9, 23; 9, 32; 9, 33; 9, 62; 9, 67; 9, 124; 10, expression_statement; 10, 11; 11, comment; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:output; 15, dictionary; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:fmf_tree; 19, call; 19, 20; 19, 21; 20, identifier:ExtendedTree; 21, argument_list; 21, 22; 22, identifier:path; 23, expression_statement; 23, 24; 24, call; 24, 25; 24, 28; 25, attribute; 25, 26; 25, 27; 26, identifier:logger; 27, identifier:debug; 28, argument_list; 28, 29; 28, 30; 28, 31; 29, string:"get FMF metadata for test (path:%s name=%s)"; 30, identifier:path; 31, identifier:name; 32, comment; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 36; 35, identifier:items; 36, list_comprehension; 36, 37; 36, 38; 36, 45; 37, identifier:x; 38, for_in_clause; 38, 39; 38, 40; 39, identifier:x; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:fmf_tree; 43, identifier:climb; 44, argument_list; 45, if_clause; 45, 46; 46, boolean_operator:and; 46, 47; 46, 57; 47, call; 47, 48; 47, 53; 48, attribute; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:x; 51, identifier:name; 52, identifier:endswith; 53, argument_list; 53, 54; 54, binary_operator:+; 54, 55; 54, 56; 55, string:"/"; 56, identifier:name; 57, comparison_operator:not; 57, 58; 57, 59; 58, string:"@"; 59, attribute; 59, 60; 59, 61; 60, identifier:x; 61, identifier:name; 62, if_statement; 62, 63; 62, 64; 63, identifier:object_list; 64, block; 64, 65; 65, return_statement; 65, 66; 66, identifier:items; 67, if_statement; 67, 68; 67, 74; 67, 81; 67, 110; 68, comparison_operator:==; 68, 69; 68, 73; 69, call; 69, 70; 69, 71; 70, identifier:len; 71, argument_list; 71, 72; 72, identifier:items; 73, integer:1; 74, block; 74, 75; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:output; 78, subscript; 78, 79; 78, 80; 79, identifier:items; 80, integer:0; 81, elif_clause; 81, 82; 81, 88; 82, comparison_operator:>; 82, 83; 82, 87; 83, call; 83, 84; 83, 85; 84, identifier:len; 85, argument_list; 85, 86; 86, identifier:items; 87, integer:1; 88, block; 88, 89; 89, raise_statement; 89, 90; 90, call; 90, 91; 90, 92; 91, identifier:Exception; 92, argument_list; 92, 93; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, string:"There is more FMF test metadata for item by name:{}({}) {}"; 96, identifier:format; 97, argument_list; 97, 98; 97, 99; 97, 103; 98, identifier:name; 99, call; 99, 100; 99, 101; 100, identifier:len; 101, argument_list; 101, 102; 102, identifier:items; 103, list_comprehension; 103, 104; 103, 107; 104, attribute; 104, 105; 104, 106; 105, identifier:x; 106, identifier:name; 107, for_in_clause; 107, 108; 107, 109; 108, identifier:x; 109, identifier:items; 110, elif_clause; 110, 111; 110, 113; 111, not_operator; 111, 112; 112, identifier:items; 113, block; 113, 114; 114, raise_statement; 114, 115; 115, call; 115, 116; 115, 117; 116, identifier:Exception; 117, argument_list; 117, 118; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, string:"Unable to get FMF metadata for: {}"; 121, identifier:format; 122, argument_list; 122, 123; 123, identifier:name; 124, return_statement; 124, 125; 125, identifier:output
def receive_fmf_metadata(name, path, object_list=False): """ search node identified by name fmfpath :param path: path to filesystem :param name: str - name as pattern to search - "/name" (prepended hierarchy item) :param object_list: bool, if true, return whole list of found items :return: Tree Object or list """ output = {} fmf_tree = ExtendedTree(path) logger.debug("get FMF metadata for test (path:%s name=%s)", path, name) # ignore items with @ in names, to avoid using unreferenced items items = [x for x in fmf_tree.climb() if x.name.endswith("/" + name) and "@" not in x.name] if object_list: return items if len(items) == 1: output = items[0] elif len(items) > 1: raise Exception("There is more FMF test metadata for item by name:{}({}) {}".format( name, len(items), [x.name for x in items])) elif not items: raise Exception("Unable to get FMF metadata for: {}".format(name)) return output
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:prune_overridden; 3, parameters; 3, 4; 4, identifier:ansi_string; 5, block; 5, 6; 5, 8; 5, 29; 5, 30; 5, 144; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:multi_seqs; 11, call; 11, 12; 11, 13; 12, identifier:set; 13, generator_expression; 13, 14; 13, 15; 13, 23; 14, identifier:p; 15, for_in_clause; 15, 16; 15, 17; 16, identifier:p; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:RE_ANSI; 20, identifier:findall; 21, argument_list; 21, 22; 22, identifier:ansi_string; 23, if_clause; 23, 24; 24, comparison_operator:in; 24, 25; 24, 26; 25, string:';'; 26, subscript; 26, 27; 26, 28; 27, identifier:p; 28, integer:1; 29, comment; 30, for_statement; 30, 31; 30, 34; 30, 35; 31, pattern_list; 31, 32; 31, 33; 32, identifier:escape; 33, identifier:codes; 34, identifier:multi_seqs; 35, block; 35, 36; 35, 51; 35, 52; 35, 73; 35, 74; 35, 109; 35, 110; 35, 125; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:r_codes; 39, call; 39, 40; 39, 41; 40, identifier:list; 41, argument_list; 41, 42; 42, call; 42, 43; 42, 44; 43, identifier:reversed; 44, argument_list; 44, 45; 45, call; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:codes; 48, identifier:split; 49, argument_list; 49, 50; 50, string:';'; 51, comment; 52, try_statement; 52, 53; 52, 69; 53, block; 53, 54; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:r_codes; 57, subscript; 57, 58; 57, 59; 58, identifier:r_codes; 59, slice; 59, 60; 59, 61; 60, colon; 61, binary_operator:+; 61, 62; 61, 68; 62, call; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:r_codes; 65, identifier:index; 66, argument_list; 66, 67; 67, string:'0'; 68, integer:1; 69, except_clause; 69, 70; 69, 71; 70, identifier:ValueError; 71, block; 71, 72; 72, pass_statement; 73, comment; 74, for_statement; 74, 75; 74, 76; 74, 77; 75, identifier:group; 76, identifier:CODE_GROUPS; 77, block; 77, 78; 78, for_statement; 78, 79; 78, 80; 78, 101; 79, identifier:pos; 80, call; 80, 81; 80, 82; 81, identifier:reversed; 82, argument_list; 82, 83; 83, subscript; 83, 84; 83, 98; 84, list_comprehension; 84, 85; 84, 86; 84, 94; 85, identifier:i; 86, for_in_clause; 86, 87; 86, 90; 87, pattern_list; 87, 88; 87, 89; 88, identifier:i; 89, identifier:n; 90, call; 90, 91; 90, 92; 91, identifier:enumerate; 92, argument_list; 92, 93; 93, identifier:r_codes; 94, if_clause; 94, 95; 95, comparison_operator:in; 95, 96; 95, 97; 96, identifier:n; 97, identifier:group; 98, slice; 98, 99; 98, 100; 99, integer:1; 100, colon; 101, block; 101, 102; 102, expression_statement; 102, 103; 103, call; 103, 104; 103, 107; 104, attribute; 104, 105; 104, 106; 105, identifier:r_codes; 106, identifier:pop; 107, argument_list; 107, 108; 108, identifier:pos; 109, comment; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:reduced_codes; 113, call; 113, 114; 113, 117; 114, attribute; 114, 115; 114, 116; 115, string:';'; 116, identifier:join; 117, argument_list; 117, 118; 118, call; 118, 119; 118, 120; 119, identifier:sorted; 120, argument_list; 120, 121; 120, 122; 121, identifier:r_codes; 122, keyword_argument; 122, 123; 122, 124; 123, identifier:key; 124, identifier:int; 125, if_statement; 125, 126; 125, 129; 126, comparison_operator:!=; 126, 127; 126, 128; 127, identifier:codes; 128, identifier:reduced_codes; 129, block; 129, 130; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 133; 132, identifier:ansi_string; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:ansi_string; 136, identifier:replace; 137, argument_list; 137, 138; 137, 139; 138, identifier:escape; 139, binary_operator:+; 139, 140; 139, 143; 140, binary_operator:+; 140, 141; 140, 142; 141, string:'\033['; 142, identifier:reduced_codes; 143, string:'m'; 144, return_statement; 144, 145; 145, identifier:ansi_string
def prune_overridden(ansi_string): """Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes. :param str ansi_string: Incoming ansi_string with ANSI color codes. :return: Color string with pruned color sequences. :rtype: str """ multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1]) # Sequences with multiple color codes. for escape, codes in multi_seqs: r_codes = list(reversed(codes.split(';'))) # Nuke everything before {/all}. try: r_codes = r_codes[:r_codes.index('0') + 1] except ValueError: pass # Thin out groups. for group in CODE_GROUPS: for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]): r_codes.pop(pos) # Done. reduced_codes = ';'.join(sorted(r_codes, key=int)) if codes != reduced_codes: ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm') return ansi_string
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:parse_input; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:tagged_string; 5, identifier:disable_colors; 6, identifier:keep_tags; 7, block; 7, 8; 7, 10; 7, 17; 7, 26; 7, 27; 7, 70; 7, 71; 7, 81; 7, 88; 7, 89; 7, 112; 7, 113; 7, 120; 7, 121; 7, 125; 7, 131; 7, 179; 7, 188; 8, expression_statement; 8, 9; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:codes; 13, call; 13, 14; 13, 15; 14, identifier:ANSICodeMapping; 15, argument_list; 15, 16; 16, identifier:tagged_string; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:output_colors; 20, call; 20, 21; 20, 22; 21, identifier:getattr; 22, argument_list; 22, 23; 22, 24; 22, 25; 23, identifier:tagged_string; 24, string:'value_colors'; 25, identifier:tagged_string; 26, comment; 27, if_statement; 27, 28; 27, 30; 28, not_operator; 28, 29; 29, identifier:keep_tags; 30, block; 30, 31; 31, for_statement; 31, 32; 31, 35; 31, 59; 32, pattern_list; 32, 33; 32, 34; 33, identifier:tag; 34, identifier:replacement; 35, generator_expression; 35, 36; 35, 50; 36, tuple; 36, 37; 36, 42; 37, binary_operator:+; 37, 38; 37, 41; 38, binary_operator:+; 38, 39; 38, 40; 39, string:'{'; 40, identifier:k; 41, string:'}'; 42, conditional_expression:if; 42, 43; 42, 44; 42, 47; 43, string:''; 44, comparison_operator:is; 44, 45; 44, 46; 45, identifier:v; 46, None; 47, binary_operator:%; 47, 48; 47, 49; 48, string:'\033[%dm'; 49, identifier:v; 50, for_in_clause; 50, 51; 50, 54; 51, pattern_list; 51, 52; 51, 53; 52, identifier:k; 53, identifier:v; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:codes; 57, identifier:items; 58, argument_list; 59, block; 59, 60; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:output_colors; 63, call; 63, 64; 63, 67; 64, attribute; 64, 65; 64, 66; 65, identifier:output_colors; 66, identifier:replace; 67, argument_list; 67, 68; 67, 69; 68, identifier:tag; 69, identifier:replacement; 70, comment; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:output_no_colors; 74, call; 74, 75; 74, 78; 75, attribute; 75, 76; 75, 77; 76, identifier:RE_ANSI; 77, identifier:sub; 78, argument_list; 78, 79; 78, 80; 79, string:''; 80, identifier:output_colors; 81, if_statement; 81, 82; 81, 83; 82, identifier:disable_colors; 83, block; 83, 84; 84, return_statement; 84, 85; 85, expression_list; 85, 86; 85, 87; 86, identifier:output_no_colors; 87, identifier:output_no_colors; 88, comment; 89, while_statement; 89, 90; 89, 91; 90, True; 91, block; 91, 92; 91, 102; 91, 108; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:simplified; 95, call; 95, 96; 95, 99; 96, attribute; 96, 97; 96, 98; 97, identifier:RE_COMBINE; 98, identifier:sub; 99, argument_list; 99, 100; 99, 101; 100, string:r'\033[\1;\2m'; 101, identifier:output_colors; 102, if_statement; 102, 103; 102, 106; 103, comparison_operator:==; 103, 104; 103, 105; 104, identifier:simplified; 105, identifier:output_colors; 106, block; 106, 107; 107, break_statement; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:output_colors; 111, identifier:simplified; 112, comment; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 116; 115, identifier:output_colors; 116, call; 116, 117; 116, 118; 117, identifier:prune_overridden; 118, argument_list; 118, 119; 119, identifier:output_colors; 120, comment; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:previous_escape; 124, None; 125, expression_statement; 125, 126; 126, assignment; 126, 127; 126, 128; 127, identifier:segments; 128, call; 128, 129; 128, 130; 129, identifier:list; 130, argument_list; 131, for_statement; 131, 132; 131, 133; 131, 145; 132, identifier:item; 133, generator_expression; 133, 134; 133, 135; 133, 143; 134, identifier:i; 135, for_in_clause; 135, 136; 135, 137; 136, identifier:i; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:RE_SPLIT; 140, identifier:split; 141, argument_list; 141, 142; 142, identifier:output_colors; 143, if_clause; 143, 144; 144, identifier:i; 145, block; 145, 146; 146, if_statement; 146, 147; 146, 153; 146, 170; 147, call; 147, 148; 147, 151; 148, attribute; 148, 149; 148, 150; 149, identifier:RE_SPLIT; 150, identifier:match; 151, argument_list; 151, 152; 152, identifier:item; 153, block; 153, 154; 154, if_statement; 154, 155; 154, 158; 155, comparison_operator:!=; 155, 156; 155, 157; 156, identifier:item; 157, identifier:previous_escape; 158, block; 158, 159; 158, 166; 159, expression_statement; 159, 160; 160, call; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:segments; 163, identifier:append; 164, argument_list; 164, 165; 165, identifier:item; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 169; 168, identifier:previous_escape; 169, identifier:item; 170, else_clause; 170, 171; 171, block; 171, 172; 172, expression_statement; 172, 173; 173, call; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:segments; 176, identifier:append; 177, argument_list; 177, 178; 178, identifier:item; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:output_colors; 182, call; 182, 183; 182, 186; 183, attribute; 183, 184; 183, 185; 184, string:''; 185, identifier:join; 186, argument_list; 186, 187; 187, identifier:segments; 188, return_statement; 188, 189; 189, expression_list; 189, 190; 189, 191; 190, identifier:output_colors; 191, identifier:output_no_colors
def parse_input(tagged_string, disable_colors, keep_tags): """Perform the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. :param str tagged_string: The input unicode value. :param bool disable_colors: Strip all colors in both outputs. :param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences. :return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors. :rtype: tuple """ codes = ANSICodeMapping(tagged_string) output_colors = getattr(tagged_string, 'value_colors', tagged_string) # Convert: '{b}{red}' -> '\033[1m\033[31m' if not keep_tags: for tag, replacement in (('{' + k + '}', '' if v is None else '\033[%dm' % v) for k, v in codes.items()): output_colors = output_colors.replace(tag, replacement) # Strip colors. output_no_colors = RE_ANSI.sub('', output_colors) if disable_colors: return output_no_colors, output_no_colors # Combine: '\033[1m\033[31m' -> '\033[1;31m' while True: simplified = RE_COMBINE.sub(r'\033[\1;\2m', output_colors) if simplified == output_colors: break output_colors = simplified # Prune: '\033[31;32;33;34;35m' -> '\033[35m' output_colors = prune_overridden(output_colors) # Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST' previous_escape = None segments = list() for item in (i for i in RE_SPLIT.split(output_colors) if i): if RE_SPLIT.match(item): if item != previous_escape: segments.append(item) previous_escape = item else: segments.append(item) output_colors = ''.join(segments) return output_colors, output_no_colors
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:memoize; 3, parameters; 3, 4; 4, identifier:method; 5, block; 5, 6; 5, 8; 5, 20; 5, 21; 5, 27; 5, 33; 5, 183; 5, 184; 5, 190; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:cache; 11, assignment; 11, 12; 11, 15; 12, attribute; 12, 13; 12, 14; 13, identifier:method; 14, identifier:cache; 15, call; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, identifier:collections; 18, identifier:OrderedDict; 19, argument_list; 20, comment; 21, expression_statement; 21, 22; 22, assignment; 22, 23; 22, 24; 23, identifier:_get; 24, attribute; 24, 25; 24, 26; 25, identifier:cache; 26, identifier:get; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:_popitem; 30, attribute; 30, 31; 30, 32; 31, identifier:cache; 32, identifier:popitem; 33, decorated_definition; 33, 34; 33, 41; 34, decorator; 34, 35; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:functools; 38, identifier:wraps; 39, argument_list; 39, 40; 40, identifier:method; 41, function_definition; 41, 42; 41, 43; 41, 50; 42, function_name:memoizer; 43, parameters; 43, 44; 43, 45; 43, 46; 43, 48; 44, identifier:instance; 45, identifier:x; 46, list_splat_pattern; 46, 47; 47, identifier:args; 48, dictionary_splat_pattern; 48, 49; 49, identifier:kwargs; 50, block; 50, 51; 50, 74; 50, 75; 50, 111; 50, 112; 50, 119; 50, 120; 50, 127; 51, if_statement; 51, 52; 51, 62; 51, 63; 52, boolean_operator:or; 52, 53; 52, 55; 53, not_operator; 53, 54; 54, identifier:_WITH_MEMOIZATION; 55, call; 55, 56; 55, 57; 56, identifier:isinstance; 57, argument_list; 57, 58; 57, 59; 58, identifier:x; 59, attribute; 59, 60; 59, 61; 60, identifier:u; 61, identifier:Quantity; 62, comment; 63, block; 63, 64; 64, return_statement; 64, 65; 65, call; 65, 66; 65, 67; 66, identifier:method; 67, argument_list; 67, 68; 67, 69; 67, 70; 67, 72; 68, identifier:instance; 69, identifier:x; 70, list_splat; 70, 71; 71, identifier:args; 72, dictionary_splat; 72, 73; 73, identifier:kwargs; 74, comment; 75, expression_statement; 75, 76; 76, assignment; 76, 77; 76, 78; 77, identifier:unique_id; 78, binary_operator:+; 78, 79; 78, 97; 79, call; 79, 80; 79, 81; 80, identifier:tuple; 81, generator_expression; 81, 82; 81, 88; 82, call; 82, 83; 82, 84; 83, identifier:float; 84, argument_list; 84, 85; 85, attribute; 85, 86; 85, 87; 86, identifier:yy; 87, identifier:value; 88, for_in_clause; 88, 89; 88, 90; 89, identifier:yy; 90, call; 90, 91; 90, 96; 91, attribute; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:instance; 94, identifier:parameters; 95, identifier:values; 96, argument_list; 97, tuple; 97, 98; 97, 101; 97, 106; 98, attribute; 98, 99; 98, 100; 99, identifier:x; 100, identifier:size; 101, call; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:x; 104, identifier:min; 105, argument_list; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:x; 109, identifier:max; 110, argument_list; 111, comment; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:key; 115, call; 115, 116; 115, 117; 116, identifier:hash; 117, argument_list; 117, 118; 118, identifier:unique_id; 119, comment; 120, expression_statement; 120, 121; 121, assignment; 121, 122; 121, 123; 122, identifier:result; 123, call; 123, 124; 123, 125; 124, identifier:_get; 125, argument_list; 125, 126; 126, identifier:key; 127, if_statement; 127, 128; 127, 131; 127, 134; 128, comparison_operator:is; 128, 129; 128, 130; 129, identifier:result; 130, None; 131, block; 131, 132; 132, return_statement; 132, 133; 133, identifier:result; 134, else_clause; 134, 135; 135, block; 135, 136; 135, 148; 135, 154; 135, 181; 136, expression_statement; 136, 137; 137, assignment; 137, 138; 137, 139; 138, identifier:result; 139, call; 139, 140; 139, 141; 140, identifier:method; 141, argument_list; 141, 142; 141, 143; 141, 144; 141, 146; 142, identifier:instance; 143, identifier:x; 144, list_splat; 144, 145; 145, identifier:args; 146, dictionary_splat; 146, 147; 147, identifier:kwargs; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 153; 150, subscript; 150, 151; 150, 152; 151, identifier:cache; 152, identifier:key; 153, identifier:result; 154, if_statement; 154, 155; 154, 161; 154, 162; 155, comparison_operator:>; 155, 156; 155, 160; 156, call; 156, 157; 156, 158; 157, identifier:len; 158, argument_list; 158, 159; 159, identifier:cache; 160, identifier:_CACHE_SIZE; 161, comment; 162, block; 162, 163; 163, expression_statement; 163, 164; 164, list_comprehension; 164, 165; 164, 169; 165, call; 165, 166; 165, 167; 166, identifier:_popitem; 167, argument_list; 167, 168; 168, False; 169, for_in_clause; 169, 170; 169, 171; 170, identifier:i; 171, call; 171, 172; 171, 173; 172, identifier:range; 173, argument_list; 173, 174; 174, call; 174, 175; 174, 176; 175, identifier:max; 176, argument_list; 176, 177; 176, 180; 177, binary_operator://; 177, 178; 177, 179; 178, identifier:_CACHE_SIZE; 179, integer:2; 180, integer:1; 181, return_statement; 181, 182; 182, identifier:result; 183, comment; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:memoizer; 188, identifier:input_object; 189, identifier:method; 190, return_statement; 190, 191; 191, identifier:memoizer
def memoize(method): """ A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls, :param method: method to be memoized :return: the decorated method """ cache = method.cache = collections.OrderedDict() # Put these two methods in the local space (faster) _get = cache.get _popitem = cache.popitem @functools.wraps(method) def memoizer(instance, x, *args, **kwargs): if not _WITH_MEMOIZATION or isinstance(x, u.Quantity): # Memoization is not active or using units, do not use memoization return method(instance, x, *args, **kwargs) # Create a tuple because a tuple is hashable unique_id = tuple(float(yy.value) for yy in instance.parameters.values()) + (x.size, x.min(), x.max()) # Create a unique identifier for this combination of inputs key = hash(unique_id) # Let's do it this way so we only look into the dictionary once result = _get(key) if result is not None: return result else: result = method(instance, x, *args, **kwargs) cache[key] = result if len(cache) > _CACHE_SIZE: # Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) ) [_popitem(False) for i in range(max(_CACHE_SIZE // 2, 1))] return result # Add the function as a "attribute" so we can access it memoizer.input_object = method return memoizer
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:_set_value; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:new_value; 6, block; 6, 7; 6, 9; 6, 38; 6, 67; 6, 68; 6, 102; 6, 103; 6, 104; 6, 128; 6, 129; 7, expression_statement; 7, 8; 8, comment; 9, if_statement; 9, 10; 9, 21; 10, boolean_operator:and; 10, 11; 10, 16; 11, comparison_operator:is; 11, 12; 11, 15; 12, attribute; 12, 13; 12, 14; 13, identifier:self; 14, identifier:min_value; 15, None; 16, comparison_operator:<; 16, 17; 16, 18; 17, identifier:new_value; 18, attribute; 18, 19; 18, 20; 19, identifier:self; 20, identifier:min_value; 21, block; 21, 22; 22, raise_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:SettingOutOfBounds; 25, argument_list; 25, 26; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, string:"Trying to set parameter {0} = {1}, which is less than the minimum allowed {2}"; 29, identifier:format; 30, argument_list; 30, 31; 30, 34; 30, 35; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:name; 34, identifier:new_value; 35, attribute; 35, 36; 35, 37; 36, identifier:self; 37, identifier:min_value; 38, if_statement; 38, 39; 38, 50; 39, boolean_operator:and; 39, 40; 39, 45; 40, comparison_operator:is; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:self; 43, identifier:max_value; 44, None; 45, comparison_operator:>; 45, 46; 45, 47; 46, identifier:new_value; 47, attribute; 47, 48; 47, 49; 48, identifier:self; 49, identifier:max_value; 50, block; 50, 51; 51, raise_statement; 51, 52; 52, call; 52, 53; 52, 54; 53, identifier:SettingOutOfBounds; 54, argument_list; 54, 55; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, string:"Trying to set parameter {0} = {1}, which is more than the maximum allowed {2}"; 58, identifier:format; 59, argument_list; 59, 60; 59, 63; 59, 64; 60, attribute; 60, 61; 60, 62; 61, identifier:self; 62, identifier:name; 63, identifier:new_value; 64, attribute; 64, 65; 64, 66; 65, identifier:self; 66, identifier:max_value; 67, comment; 68, if_statement; 68, 69; 68, 74; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:self; 72, identifier:has_auxiliary_variable; 73, argument_list; 74, block; 74, 75; 75, with_statement; 75, 76; 75, 83; 76, with_clause; 76, 77; 77, with_item; 77, 78; 78, call; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:warnings; 81, identifier:catch_warnings; 82, argument_list; 83, block; 83, 84; 83, 92; 84, expression_statement; 84, 85; 85, call; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:warnings; 88, identifier:simplefilter; 89, argument_list; 89, 90; 89, 91; 90, string:"always"; 91, identifier:RuntimeWarning; 92, expression_statement; 92, 93; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, identifier:warnings; 96, identifier:warn; 97, argument_list; 97, 98; 97, 101; 98, concatenated_string; 98, 99; 98, 100; 99, string:"You are trying to assign to a parameter which is either linked or "; 100, string:"has auxiliary variables. The assignment has no effect."; 101, identifier:RuntimeWarning; 102, comment; 103, comment; 104, if_statement; 104, 105; 104, 110; 104, 115; 105, comparison_operator:is; 105, 106; 105, 109; 106, attribute; 106, 107; 106, 108; 107, identifier:self; 108, identifier:_transformation; 109, None; 110, block; 110, 111; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:new_internal_value; 114, identifier:new_value; 115, else_clause; 115, 116; 116, block; 116, 117; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:new_internal_value; 120, call; 120, 121; 120, 126; 121, attribute; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:self; 124, identifier:_transformation; 125, identifier:forward; 126, argument_list; 126, 127; 127, identifier:new_value; 128, comment; 129, if_statement; 129, 130; 129, 135; 129, 136; 130, comparison_operator:!=; 130, 131; 130, 132; 131, identifier:new_internal_value; 132, attribute; 132, 133; 132, 134; 133, identifier:self; 134, identifier:_internal_value; 135, comment; 136, block; 136, 137; 136, 143; 136, 144; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 142; 139, attribute; 139, 140; 139, 141; 140, identifier:self; 141, identifier:_internal_value; 142, identifier:new_internal_value; 143, comment; 144, for_statement; 144, 145; 144, 146; 144, 149; 145, identifier:callback; 146, attribute; 146, 147; 146, 148; 147, identifier:self; 148, identifier:_callbacks; 149, block; 149, 150; 150, try_statement; 150, 151; 150, 157; 151, block; 151, 152; 152, expression_statement; 152, 153; 153, call; 153, 154; 153, 155; 154, identifier:callback; 155, argument_list; 155, 156; 156, identifier:self; 157, except_clause; 157, 158; 158, block; 158, 159; 159, raise_statement; 159, 160; 160, call; 160, 161; 160, 162; 161, identifier:NotCallableOrErrorInCall; 162, argument_list; 162, 163; 163, binary_operator:%; 163, 164; 163, 165; 164, string:"Could not call callback for parameter %s"; 165, attribute; 165, 166; 165, 167; 166, identifier:self; 167, identifier:name
def _set_value(self, new_value): """Sets the current value of the parameter, ensuring that it is within the allowed range.""" if self.min_value is not None and new_value < self.min_value: raise SettingOutOfBounds( "Trying to set parameter {0} = {1}, which is less than the minimum allowed {2}".format( self.name, new_value, self.min_value)) if self.max_value is not None and new_value > self.max_value: raise SettingOutOfBounds( "Trying to set parameter {0} = {1}, which is more than the maximum allowed {2}".format( self.name, new_value, self.max_value)) # Issue a warning if there is an auxiliary variable, as the setting does not have any effect if self.has_auxiliary_variable(): with warnings.catch_warnings(): warnings.simplefilter("always", RuntimeWarning) warnings.warn("You are trying to assign to a parameter which is either linked or " "has auxiliary variables. The assignment has no effect.", RuntimeWarning) # Save the value as a pure floating point to avoid the overhead of the astropy.units machinery when # not needed if self._transformation is None: new_internal_value = new_value else: new_internal_value = self._transformation.forward(new_value) # If the parameter has changed, update its value and call the callbacks if needed if new_internal_value != self._internal_value: # Update self._internal_value = new_internal_value # Call the callbacks (if any) for callback in self._callbacks: try: callback(self) except: raise NotCallableOrErrorInCall("Could not call callback for parameter %s" % self.name)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:set_uninformative_prior; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:prior_class; 6, block; 6, 7; 6, 9; 6, 15; 6, 61; 6, 108; 6, 124; 6, 140; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:prior_instance; 12, call; 12, 13; 12, 14; 13, identifier:prior_class; 14, argument_list; 15, if_statement; 15, 16; 15, 21; 15, 33; 16, comparison_operator:is; 16, 17; 16, 20; 17, attribute; 17, 18; 17, 19; 18, identifier:self; 19, identifier:min_value; 20, None; 21, block; 21, 22; 22, raise_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:ParameterMustHaveBounds; 25, argument_list; 25, 26; 26, binary_operator:%; 26, 27; 26, 30; 27, concatenated_string; 27, 28; 27, 29; 28, string:"Parameter %s does not have a defined minimum. Set one first, then re-run "; 29, string:"set_uninformative_prior"; 30, attribute; 30, 31; 30, 32; 31, identifier:self; 32, identifier:path; 33, else_clause; 33, 34; 34, block; 34, 35; 35, try_statement; 35, 36; 35, 45; 36, block; 36, 37; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:prior_instance; 41, identifier:lower_bound; 42, attribute; 42, 43; 42, 44; 43, identifier:self; 44, identifier:min_value; 45, except_clause; 45, 46; 45, 47; 46, identifier:SettingOutOfBounds; 47, block; 47, 48; 48, raise_statement; 48, 49; 49, call; 49, 50; 49, 51; 50, identifier:SettingOutOfBounds; 51, argument_list; 51, 52; 52, binary_operator:%; 52, 53; 52, 54; 53, string:"Cannot use minimum of %s for prior %s"; 54, tuple; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:self; 57, identifier:min_value; 58, attribute; 58, 59; 58, 60; 59, identifier:prior_instance; 60, identifier:name; 61, if_statement; 61, 62; 61, 67; 61, 79; 62, comparison_operator:is; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:self; 65, identifier:max_value; 66, None; 67, block; 67, 68; 68, raise_statement; 68, 69; 69, call; 69, 70; 69, 71; 70, identifier:ParameterMustHaveBounds; 71, argument_list; 71, 72; 72, binary_operator:%; 72, 73; 72, 76; 73, concatenated_string; 73, 74; 73, 75; 74, string:"Parameter %s does not have a defined maximum. Set one first, then re-run "; 75, string:"set_uninformative_prior"; 76, attribute; 76, 77; 76, 78; 77, identifier:self; 78, identifier:path; 79, else_clause; 79, 80; 79, 81; 80, comment; 81, block; 81, 82; 82, try_statement; 82, 83; 82, 92; 83, block; 83, 84; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:prior_instance; 88, identifier:upper_bound; 89, attribute; 89, 90; 89, 91; 90, identifier:self; 91, identifier:max_value; 92, except_clause; 92, 93; 92, 94; 93, identifier:SettingOutOfBounds; 94, block; 94, 95; 95, raise_statement; 95, 96; 96, call; 96, 97; 96, 98; 97, identifier:SettingOutOfBounds; 98, argument_list; 98, 99; 99, binary_operator:%; 99, 100; 99, 101; 100, string:"Cannot use maximum of %s for prior %s"; 101, tuple; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:self; 104, identifier:max_value; 105, attribute; 105, 106; 105, 107; 106, identifier:prior_instance; 107, identifier:name; 108, assert_statement; 108, 109; 108, 119; 109, call; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:np; 112, identifier:isfinite; 113, argument_list; 113, 114; 114, attribute; 114, 115; 114, 118; 115, attribute; 115, 116; 115, 117; 116, identifier:prior_instance; 117, identifier:upper_bound; 118, identifier:value; 119, binary_operator:%; 119, 120; 119, 121; 120, string:"The parameter %s must have a finite maximum"; 121, attribute; 121, 122; 121, 123; 122, identifier:self; 123, identifier:name; 124, assert_statement; 124, 125; 124, 135; 125, call; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:np; 128, identifier:isfinite; 129, argument_list; 129, 130; 130, attribute; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:prior_instance; 133, identifier:lower_bound; 134, identifier:value; 135, binary_operator:%; 135, 136; 135, 137; 136, string:"The parameter %s must have a finite minimum"; 137, attribute; 137, 138; 137, 139; 138, identifier:self; 139, identifier:name; 140, expression_statement; 140, 141; 141, call; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:self; 144, identifier:_set_prior; 145, argument_list; 145, 146; 146, identifier:prior_instance
def set_uninformative_prior(self, prior_class): """ Sets the prior for the parameter to a uniform prior between the current minimum and maximum, or a log-uniform prior between the current minimum and maximum. NOTE: if the current minimum and maximum are not defined, the default bounds for the prior class will be used. :param prior_class : the class to be used as prior (either Log_uniform_prior or Uniform_prior, or a class which provide a lower_bound and an upper_bound properties) :return: (none) """ prior_instance = prior_class() if self.min_value is None: raise ParameterMustHaveBounds("Parameter %s does not have a defined minimum. Set one first, then re-run " "set_uninformative_prior" % self.path) else: try: prior_instance.lower_bound = self.min_value except SettingOutOfBounds: raise SettingOutOfBounds("Cannot use minimum of %s for prior %s" % (self.min_value, prior_instance.name)) if self.max_value is None: raise ParameterMustHaveBounds("Parameter %s does not have a defined maximum. Set one first, then re-run " "set_uninformative_prior" % self.path) else: # pragma: no cover try: prior_instance.upper_bound = self.max_value except SettingOutOfBounds: raise SettingOutOfBounds("Cannot use maximum of %s for prior %s" % (self.max_value, prior_instance.name)) assert np.isfinite(prior_instance.upper_bound.value),"The parameter %s must have a finite maximum" % self.name assert np.isfinite(prior_instance.lower_bound.value),"The parameter %s must have a finite minimum" % self.name self._set_prior(prior_instance)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:find_library; 3, parameters; 3, 4; 3, 5; 4, identifier:library_root; 5, default_parameter; 5, 6; 5, 7; 6, identifier:additional_places; 7, None; 8, block; 8, 9; 8, 11; 8, 12; 8, 13; 8, 24; 9, expression_statement; 9, 10; 10, comment; 11, comment; 12, comment; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:first_guess; 16, call; 16, 17; 16, 22; 17, attribute; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:ctypes; 20, identifier:util; 21, identifier:find_library; 22, argument_list; 22, 23; 23, identifier:library_root; 24, if_statement; 24, 25; 24, 28; 24, 29; 24, 99; 25, comparison_operator:is; 25, 26; 25, 27; 26, identifier:first_guess; 27, None; 28, comment; 29, block; 29, 30; 30, if_statement; 30, 31; 30, 45; 30, 46; 30, 47; 30, 55; 30, 87; 31, comparison_operator:>=; 31, 32; 31, 44; 32, call; 32, 33; 32, 42; 33, attribute; 33, 34; 33, 41; 34, call; 34, 35; 34, 40; 35, attribute; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:sys; 38, identifier:platform; 39, identifier:lower; 40, argument_list; 41, identifier:find; 42, argument_list; 42, 43; 43, string:"linux"; 44, integer:0; 45, comment; 46, comment; 47, block; 47, 48; 48, return_statement; 48, 49; 49, expression_list; 49, 50; 49, 54; 50, call; 50, 51; 50, 52; 51, identifier:sanitize_lib_name; 52, argument_list; 52, 53; 53, identifier:first_guess; 54, None; 55, elif_clause; 55, 56; 55, 70; 55, 71; 55, 72; 56, comparison_operator:>=; 56, 57; 56, 69; 57, call; 57, 58; 57, 67; 58, attribute; 58, 59; 58, 66; 59, call; 59, 60; 59, 65; 60, attribute; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:sys; 63, identifier:platform; 64, identifier:lower; 65, argument_list; 66, identifier:find; 67, argument_list; 67, 68; 68, string:"darwin"; 69, integer:0; 70, comment; 71, comment; 72, block; 72, 73; 73, return_statement; 73, 74; 74, expression_list; 74, 75; 74, 79; 75, call; 75, 76; 75, 77; 76, identifier:sanitize_lib_name; 77, argument_list; 77, 78; 78, identifier:first_guess; 79, call; 79, 80; 79, 85; 80, attribute; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:os; 83, identifier:path; 84, identifier:dirname; 85, argument_list; 85, 86; 86, identifier:first_guess; 87, else_clause; 87, 88; 87, 89; 88, comment; 89, block; 89, 90; 90, raise_statement; 90, 91; 91, call; 91, 92; 91, 93; 92, identifier:NotImplementedError; 93, argument_list; 93, 94; 94, binary_operator:%; 94, 95; 94, 96; 95, string:"Platform %s is not supported"; 96, attribute; 96, 97; 96, 98; 97, identifier:sys; 98, identifier:platform; 99, else_clause; 99, 100; 99, 101; 99, 102; 99, 103; 100, comment; 101, comment; 102, comment; 103, block; 103, 104; 103, 183; 103, 195; 103, 196; 103, 200; 103, 204; 103, 292; 104, if_statement; 104, 105; 104, 119; 104, 120; 104, 138; 104, 172; 105, comparison_operator:>=; 105, 106; 105, 118; 106, call; 106, 107; 106, 116; 107, attribute; 107, 108; 107, 115; 108, call; 108, 109; 108, 114; 109, attribute; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:sys; 112, identifier:platform; 113, identifier:lower; 114, argument_list; 115, identifier:find; 116, argument_list; 116, 117; 117, string:"linux"; 118, integer:0; 119, comment; 120, block; 120, 121; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:possible_locations; 124, call; 124, 125; 124, 136; 125, attribute; 125, 126; 125, 135; 126, call; 126, 127; 126, 132; 127, attribute; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:os; 130, identifier:environ; 131, identifier:get; 132, argument_list; 132, 133; 132, 134; 133, string:"LD_LIBRARY_PATH"; 134, string:""; 135, identifier:split; 136, argument_list; 136, 137; 137, string:":"; 138, elif_clause; 138, 139; 138, 153; 138, 154; 139, comparison_operator:>=; 139, 140; 139, 152; 140, call; 140, 141; 140, 150; 141, attribute; 141, 142; 141, 149; 142, call; 142, 143; 142, 148; 143, attribute; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:sys; 146, identifier:platform; 147, identifier:lower; 148, argument_list; 149, identifier:find; 150, argument_list; 150, 151; 151, string:"darwin"; 152, integer:0; 153, comment; 154, block; 154, 155; 155, expression_statement; 155, 156; 156, assignment; 156, 157; 156, 158; 157, identifier:possible_locations; 158, call; 158, 159; 158, 170; 159, attribute; 159, 160; 159, 169; 160, call; 160, 161; 160, 166; 161, attribute; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, identifier:os; 164, identifier:environ; 165, identifier:get; 166, argument_list; 166, 167; 166, 168; 167, string:"DYLD_LIBRARY_PATH"; 168, string:""; 169, identifier:split; 170, argument_list; 170, 171; 171, string:":"; 172, else_clause; 172, 173; 173, block; 173, 174; 174, raise_statement; 174, 175; 175, call; 175, 176; 175, 177; 176, identifier:NotImplementedError; 177, argument_list; 177, 178; 178, binary_operator:%; 178, 179; 178, 180; 179, string:"Platform %s is not supported"; 180, attribute; 180, 181; 180, 182; 181, identifier:sys; 182, identifier:platform; 183, if_statement; 183, 184; 183, 187; 184, comparison_operator:is; 184, 185; 184, 186; 185, identifier:additional_places; 186, None; 187, block; 187, 188; 188, expression_statement; 188, 189; 189, call; 189, 190; 189, 193; 190, attribute; 190, 191; 190, 192; 191, identifier:possible_locations; 192, identifier:extend; 193, argument_list; 193, 194; 194, identifier:additional_places; 195, comment; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 199; 198, identifier:library_name; 199, None; 200, expression_statement; 200, 201; 201, assignment; 201, 202; 201, 203; 202, identifier:library_dir; 203, None; 204, for_statement; 204, 205; 204, 206; 204, 207; 205, identifier:search_path; 206, identifier:possible_locations; 207, block; 207, 208; 207, 216; 207, 235; 207, 286; 208, if_statement; 208, 209; 208, 212; 208, 213; 208, 214; 209, comparison_operator:==; 209, 210; 209, 211; 210, identifier:search_path; 211, string:""; 212, comment; 213, comment; 214, block; 214, 215; 215, continue_statement; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 219; 218, identifier:results; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:glob; 222, identifier:glob; 223, argument_list; 223, 224; 224, call; 224, 225; 224, 230; 225, attribute; 225, 226; 225, 229; 226, attribute; 226, 227; 226, 228; 227, identifier:os; 228, identifier:path; 229, identifier:join; 230, argument_list; 230, 231; 230, 232; 231, identifier:search_path; 232, binary_operator:%; 232, 233; 232, 234; 233, string:"lib%s*"; 234, identifier:library_root; 235, if_statement; 235, 236; 235, 242; 235, 243; 235, 244; 235, 283; 236, comparison_operator:>=; 236, 237; 236, 241; 237, call; 237, 238; 237, 239; 238, identifier:len; 239, argument_list; 239, 240; 240, identifier:results; 241, integer:1; 242, comment; 243, comment; 244, block; 244, 245; 245, for_statement; 245, 246; 245, 247; 245, 248; 246, identifier:result; 247, identifier:results; 248, block; 248, 249; 249, if_statement; 249, 250; 249, 268; 249, 270; 250, comparison_operator:is; 250, 251; 250, 267; 251, call; 251, 252; 251, 255; 252, attribute; 252, 253; 252, 254; 253, identifier:re; 254, identifier:match; 255, argument_list; 255, 256; 255, 259; 256, binary_operator:%; 256, 257; 256, 258; 257, string:"lib%s[\-_\.]"; 258, identifier:library_root; 259, call; 259, 260; 259, 265; 260, attribute; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, identifier:os; 263, identifier:path; 264, identifier:basename; 265, argument_list; 265, 266; 266, identifier:result; 267, None; 268, block; 268, 269; 269, continue_statement; 270, else_clause; 270, 271; 270, 272; 270, 273; 271, comment; 272, comment; 273, block; 273, 274; 273, 278; 273, 282; 274, expression_statement; 274, 275; 275, assignment; 275, 276; 275, 277; 276, identifier:library_name; 277, identifier:result; 278, expression_statement; 278, 279; 279, assignment; 279, 280; 279, 281; 280, identifier:library_dir; 281, identifier:search_path; 282, break_statement; 283, else_clause; 283, 284; 284, block; 284, 285; 285, continue_statement; 286, if_statement; 286, 287; 286, 290; 287, comparison_operator:is; 287, 288; 287, 289; 288, identifier:library_name; 289, None; 290, block; 290, 291; 291, break_statement; 292, if_statement; 292, 293; 292, 296; 292, 301; 293, comparison_operator:is; 293, 294; 293, 295; 294, identifier:library_name; 295, None; 296, block; 296, 297; 297, return_statement; 297, 298; 298, expression_list; 298, 299; 298, 300; 299, None; 300, None; 301, else_clause; 301, 302; 301, 303; 301, 304; 302, comment; 303, comment; 304, block; 304, 305; 305, return_statement; 305, 306; 306, expression_list; 306, 307; 306, 311; 307, call; 307, 308; 307, 309; 308, identifier:sanitize_lib_name; 309, argument_list; 309, 310; 310, identifier:library_name; 311, identifier:library_dir
def find_library(library_root, additional_places=None): """ Returns the name of the library without extension :param library_root: root of the library to search, for example "cfitsio_" will match libcfitsio_1.2.3.4.so :return: the name of the library found (NOTE: this is *not* the path), and a directory path if the library is not in the system paths (and None otherwise). The name of libcfitsio_1.2.3.4.so will be cfitsio_1.2.3.4, in other words, it will be what is needed to be passed to the linker during a c/c++ compilation, in the -l option """ # find_library searches for all system paths in a system independent way (but NOT those defined in # LD_LIBRARY_PATH or DYLD_LIBRARY_PATH) first_guess = ctypes.util.find_library(library_root) if first_guess is not None: # Found in one of the system paths if sys.platform.lower().find("linux") >= 0: # On linux the linker already knows about these paths, so we # can return None as path return sanitize_lib_name(first_guess), None elif sys.platform.lower().find("darwin") >= 0: # On Mac we still need to return the path, because the linker sometimes # does not look into it return sanitize_lib_name(first_guess), os.path.dirname(first_guess) else: # Windows is not supported raise NotImplementedError("Platform %s is not supported" % sys.platform) else: # could not find it. Let's examine LD_LIBRARY_PATH or DYLD_LIBRARY_PATH # (if they sanitize_lib_name(first_guess), are not defined, possible_locations will become [""] which will # be handled by the next loop) if sys.platform.lower().find("linux") >= 0: # Unix / linux possible_locations = os.environ.get("LD_LIBRARY_PATH", "").split(":") elif sys.platform.lower().find("darwin") >= 0: # Mac possible_locations = os.environ.get("DYLD_LIBRARY_PATH", "").split(":") else: raise NotImplementedError("Platform %s is not supported" % sys.platform) if additional_places is not None: possible_locations.extend(additional_places) # Now look into the search paths library_name = None library_dir = None for search_path in possible_locations: if search_path == "": # This can happen if there are more than one :, or if nor LD_LIBRARY_PATH # nor DYLD_LIBRARY_PATH are defined (because of the default use above for os.environ.get) continue results = glob.glob(os.path.join(search_path, "lib%s*" % library_root)) if len(results) >= 1: # Results contain things like libXS.so, libXSPlot.so, libXSpippo.so # If we are looking for libXS.so, we need to make sure that we get the right one! for result in results: if re.match("lib%s[\-_\.]" % library_root, os.path.basename(result)) is None: continue else: # FOUND IT # This is the full path of the library, like /usr/lib/libcfitsio_1.2.3.4 library_name = result library_dir = search_path break else: continue if library_name is not None: break if library_name is None: return None, None else: # Sanitize the library name to get from the fully-qualified path to just the library name # (/usr/lib/libgfortran.so.3.0 becomes gfortran) return sanitize_lib_name(library_name), library_dir
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:LDA_discriminants; 3, parameters; 3, 4; 3, 5; 4, identifier:x; 5, identifier:labels; 6, block; 6, 7; 6, 9; 6, 10; 6, 28; 6, 29; 6, 39; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, try_statement; 10, 11; 10, 21; 11, block; 11, 12; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:x; 15, call; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, identifier:np; 18, identifier:array; 19, argument_list; 19, 20; 20, identifier:x; 21, except_clause; 21, 22; 22, block; 22, 23; 23, raise_statement; 23, 24; 24, call; 24, 25; 24, 26; 25, identifier:ValueError; 26, argument_list; 26, 27; 27, string:'Impossible to convert x to a numpy array.'; 28, comment; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 34; 31, pattern_list; 31, 32; 31, 33; 32, identifier:eigen_values; 33, identifier:eigen_vectors; 34, call; 34, 35; 34, 36; 35, identifier:LDA_base; 36, argument_list; 36, 37; 36, 38; 37, identifier:x; 38, identifier:labels; 39, return_statement; 39, 40; 40, subscript; 40, 41; 40, 42; 41, identifier:eigen_values; 42, call; 42, 43; 42, 48; 43, attribute; 43, 44; 43, 47; 44, parenthesized_expression; 44, 45; 45, unary_operator:-; 45, 46; 46, identifier:eigen_values; 47, identifier:argsort; 48, argument_list
def LDA_discriminants(x, labels): """ Linear Discriminant Analysis helper for determination how many columns of data should be reduced. **Args:** * `x` : input matrix (2d array), every row represents new sample * `labels` : list of labels (iterable), every item should be label for \ sample with corresponding index **Returns:** * `discriminants` : array of eigenvalues sorted in descending order """ # validate inputs try: x = np.array(x) except: raise ValueError('Impossible to convert x to a numpy array.') # make the LDA eigen_values, eigen_vectors = LDA_base(x, labels) return eigen_values[(-eigen_values).argsort()]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 13; 2, function_name:train; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 10; 4, identifier:self; 5, identifier:x; 6, identifier:d; 7, default_parameter; 7, 8; 7, 9; 8, identifier:epochs; 9, integer:10; 10, default_parameter; 10, 11; 10, 12; 11, identifier:shuffle; 12, False; 13, block; 13, 14; 13, 16; 13, 17; 13, 24; 13, 38; 13, 56; 13, 98; 13, 125; 13, 126; 13, 161; 13, 170; 13, 171; 13, 207; 13, 208; 13, 278; 14, expression_statement; 14, 15; 15, comment; 16, comment; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 20; 19, identifier:N; 20, call; 20, 21; 20, 22; 21, identifier:len; 22, argument_list; 22, 23; 23, identifier:x; 24, if_statement; 24, 25; 24, 32; 25, not_operator; 25, 26; 26, comparison_operator:==; 26, 27; 26, 31; 27, call; 27, 28; 27, 29; 28, identifier:len; 29, argument_list; 29, 30; 30, identifier:d; 31, identifier:N; 32, block; 32, 33; 33, raise_statement; 33, 34; 34, call; 34, 35; 34, 36; 35, identifier:ValueError; 36, argument_list; 36, 37; 37, string:'The length of vector d and matrix x must agree.'; 38, if_statement; 38, 39; 38, 50; 39, not_operator; 39, 40; 40, comparison_operator:==; 40, 41; 40, 47; 41, call; 41, 42; 41, 43; 42, identifier:len; 43, argument_list; 43, 44; 44, subscript; 44, 45; 44, 46; 45, identifier:x; 46, integer:0; 47, attribute; 47, 48; 47, 49; 48, identifier:self; 49, identifier:n_input; 50, block; 50, 51; 51, raise_statement; 51, 52; 52, call; 52, 53; 52, 54; 53, identifier:ValueError; 54, argument_list; 54, 55; 55, string:'The number of network inputs is not correct.'; 56, if_statement; 56, 57; 56, 62; 56, 79; 57, comparison_operator:==; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:self; 60, identifier:outputs; 61, integer:1; 62, block; 62, 63; 63, if_statement; 63, 64; 63, 73; 64, not_operator; 64, 65; 65, comparison_operator:==; 65, 66; 65, 72; 66, call; 66, 67; 66, 68; 67, identifier:len; 68, argument_list; 68, 69; 69, attribute; 69, 70; 69, 71; 70, identifier:d; 71, identifier:shape; 72, integer:1; 73, block; 73, 74; 74, raise_statement; 74, 75; 75, call; 75, 76; 75, 77; 76, identifier:ValueError; 77, argument_list; 77, 78; 78, string:'For one output MLP the d must have one dimension'; 79, else_clause; 79, 80; 80, block; 80, 81; 81, if_statement; 81, 82; 81, 92; 82, not_operator; 82, 83; 83, comparison_operator:==; 83, 84; 83, 89; 84, subscript; 84, 85; 84, 88; 85, attribute; 85, 86; 85, 87; 86, identifier:d; 87, identifier:shape; 88, integer:1; 89, attribute; 89, 90; 89, 91; 90, identifier:self; 91, identifier:outputs; 92, block; 92, 93; 93, raise_statement; 93, 94; 94, call; 94, 95; 94, 96; 95, identifier:ValueError; 96, argument_list; 96, 97; 97, string:'The number of outputs must agree with number of columns in d'; 98, try_statement; 98, 99; 98, 118; 99, block; 99, 100; 99, 109; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 103; 102, identifier:x; 103, call; 103, 104; 103, 107; 104, attribute; 104, 105; 104, 106; 105, identifier:np; 106, identifier:array; 107, argument_list; 107, 108; 108, identifier:x; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 112; 111, identifier:d; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:np; 115, identifier:array; 116, argument_list; 116, 117; 117, identifier:d; 118, except_clause; 118, 119; 119, block; 119, 120; 120, raise_statement; 120, 121; 121, call; 121, 122; 121, 123; 122, identifier:ValueError; 123, argument_list; 123, 124; 124, string:'Impossible to convert x or d to a numpy array'; 125, comment; 126, if_statement; 126, 127; 126, 132; 126, 144; 127, comparison_operator:==; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:self; 130, identifier:outputs; 131, integer:1; 132, block; 132, 133; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:e; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:np; 139, identifier:zeros; 140, argument_list; 140, 141; 141, binary_operator:*; 141, 142; 141, 143; 142, identifier:epochs; 143, identifier:N; 144, else_clause; 144, 145; 145, block; 145, 146; 146, expression_statement; 146, 147; 147, assignment; 147, 148; 147, 149; 148, identifier:e; 149, call; 149, 150; 149, 153; 150, attribute; 150, 151; 150, 152; 151, identifier:np; 152, identifier:zeros; 153, argument_list; 153, 154; 154, tuple; 154, 155; 154, 158; 155, binary_operator:*; 155, 156; 155, 157; 156, identifier:epochs; 157, identifier:N; 158, attribute; 158, 159; 158, 160; 159, identifier:self; 160, identifier:outputs; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:MSE; 164, call; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:np; 167, identifier:zeros; 168, argument_list; 168, 169; 169, identifier:epochs; 170, comment; 171, if_statement; 171, 172; 171, 173; 172, identifier:shuffle; 173, block; 173, 174; 173, 186; 173, 195; 173, 201; 174, expression_statement; 174, 175; 175, assignment; 175, 176; 175, 177; 176, identifier:randomize; 177, call; 177, 178; 177, 181; 178, attribute; 178, 179; 178, 180; 179, identifier:np; 180, identifier:arange; 181, argument_list; 181, 182; 182, call; 182, 183; 182, 184; 183, identifier:len; 184, argument_list; 184, 185; 185, identifier:x; 186, expression_statement; 186, 187; 187, call; 187, 188; 187, 193; 188, attribute; 188, 189; 188, 192; 189, attribute; 189, 190; 189, 191; 190, identifier:np; 191, identifier:random; 192, identifier:shuffle; 193, argument_list; 193, 194; 194, identifier:randomize; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:x; 198, subscript; 198, 199; 198, 200; 199, identifier:x; 200, identifier:randomize; 201, expression_statement; 201, 202; 202, assignment; 202, 203; 202, 204; 203, identifier:d; 204, subscript; 204, 205; 204, 206; 205, identifier:d; 206, identifier:randomize; 207, comment; 208, for_statement; 208, 209; 208, 210; 208, 214; 209, identifier:epoch; 210, call; 210, 211; 210, 212; 211, identifier:range; 212, argument_list; 212, 213; 213, identifier:epochs; 214, block; 214, 215; 214, 249; 215, for_statement; 215, 216; 215, 217; 215, 221; 216, identifier:k; 217, call; 217, 218; 217, 219; 218, identifier:range; 219, argument_list; 219, 220; 220, identifier:N; 221, block; 221, 222; 221, 231; 222, expression_statement; 222, 223; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:self; 226, identifier:predict; 227, argument_list; 227, 228; 228, subscript; 228, 229; 228, 230; 229, identifier:x; 230, identifier:k; 231, expression_statement; 231, 232; 232, assignment; 232, 233; 232, 241; 233, subscript; 233, 234; 233, 235; 234, identifier:e; 235, binary_operator:+; 235, 236; 235, 240; 236, parenthesized_expression; 236, 237; 237, binary_operator:*; 237, 238; 237, 239; 238, identifier:epoch; 239, identifier:N; 240, identifier:k; 241, call; 241, 242; 241, 245; 242, attribute; 242, 243; 242, 244; 243, identifier:self; 244, identifier:update; 245, argument_list; 245, 246; 246, subscript; 246, 247; 246, 248; 247, identifier:d; 248, identifier:k; 249, expression_statement; 249, 250; 250, assignment; 250, 251; 250, 254; 251, subscript; 251, 252; 251, 253; 252, identifier:MSE; 253, identifier:epoch; 254, binary_operator:/; 254, 255; 254, 277; 255, call; 255, 256; 255, 259; 256, attribute; 256, 257; 256, 258; 257, identifier:np; 258, identifier:sum; 259, argument_list; 259, 260; 260, binary_operator:**; 260, 261; 260, 276; 261, subscript; 261, 262; 261, 263; 262, identifier:e; 263, slice; 263, 264; 263, 267; 263, 268; 264, binary_operator:*; 264, 265; 264, 266; 265, identifier:epoch; 266, identifier:N; 267, colon; 268, binary_operator:-; 268, 269; 268, 275; 269, binary_operator:*; 269, 270; 269, 274; 270, parenthesized_expression; 270, 271; 271, binary_operator:+; 271, 272; 271, 273; 272, identifier:epoch; 273, integer:1; 274, identifier:N; 275, integer:1; 276, integer:2; 277, identifier:N; 278, return_statement; 278, 279; 279, expression_list; 279, 280; 279, 281; 280, identifier:e; 281, identifier:MSE
def train(self, x, d, epochs=10, shuffle=False): """ Function for batch training of MLP. **Args:** * `x` : input array (2-dimensional array). Every row represents one input vector (features). * `d` : input array (n-dimensional array). Every row represents target for one input vector. Target can be one or more values (in case of multiple outputs). **Kwargs:** * `epochs` : amount of epochs (int). That means how many times the MLP will iterate over the passed set of data (`x`, `d`). * `shuffle` : if true, the order of inputs and outpust are shuffled (bool). That means the pairs input-output are in different order in every epoch. **Returns:** * `e`: output vector (m-dimensional array). Every row represents error (or errors) for an input and output in given epoch. The size of this array is length of provided data times amount of epochs (`N*epochs`). * `MSE` : mean squared error (1-dimensional array). Every value stands for MSE of one epoch. """ # measure the data and check if the dimmension agree N = len(x) if not len(d) == N: raise ValueError('The length of vector d and matrix x must agree.') if not len(x[0]) == self.n_input: raise ValueError('The number of network inputs is not correct.') if self.outputs == 1: if not len(d.shape) == 1: raise ValueError('For one output MLP the d must have one dimension') else: if not d.shape[1] == self.outputs: raise ValueError('The number of outputs must agree with number of columns in d') try: x = np.array(x) d = np.array(d) except: raise ValueError('Impossible to convert x or d to a numpy array') # create empty arrays if self.outputs == 1: e = np.zeros(epochs*N) else: e = np.zeros((epochs*N, self.outputs)) MSE = np.zeros(epochs) # shuffle data if demanded if shuffle: randomize = np.arange(len(x)) np.random.shuffle(randomize) x = x[randomize] d = d[randomize] # adaptation loop for epoch in range(epochs): for k in range(N): self.predict(x[k]) e[(epoch*N)+k] = self.update(d[k]) MSE[epoch] = np.sum(e[epoch*N:(epoch+1)*N-1]**2) / N return e, MSE
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:PCA_components; 3, parameters; 3, 4; 4, identifier:x; 5, block; 5, 6; 5, 8; 5, 9; 5, 27; 5, 28; 5, 48; 5, 49; 5, 63; 5, 64; 6, expression_statement; 6, 7; 7, comment; 8, comment; 9, try_statement; 9, 10; 9, 20; 10, block; 10, 11; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:x; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:np; 17, identifier:array; 18, argument_list; 18, 19; 19, identifier:x; 20, except_clause; 20, 21; 21, block; 21, 22; 22, raise_statement; 22, 23; 23, call; 23, 24; 23, 25; 24, identifier:ValueError; 25, argument_list; 25, 26; 26, string:'Impossible to convert x to a numpy array.'; 27, comment; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 33; 30, pattern_list; 30, 31; 30, 32; 31, identifier:eigen_values; 32, identifier:eigen_vectors; 33, call; 33, 34; 33, 39; 34, attribute; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:np; 37, identifier:linalg; 38, identifier:eig; 39, argument_list; 39, 40; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:np; 43, identifier:cov; 44, argument_list; 44, 45; 45, attribute; 45, 46; 45, 47; 46, identifier:x; 47, identifier:T; 48, comment; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:eigen_order; 52, subscript; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:eigen_vectors; 55, identifier:T; 56, call; 56, 57; 56, 62; 57, attribute; 57, 58; 57, 61; 58, parenthesized_expression; 58, 59; 59, unary_operator:-; 59, 60; 60, identifier:eigen_values; 61, identifier:argsort; 62, argument_list; 63, comment; 64, return_statement; 64, 65; 65, subscript; 65, 66; 65, 67; 66, identifier:eigen_values; 67, call; 67, 68; 67, 73; 68, attribute; 68, 69; 68, 72; 69, parenthesized_expression; 69, 70; 70, unary_operator:-; 70, 71; 71, identifier:eigen_values; 72, identifier:argsort; 73, argument_list
def PCA_components(x): """ Principal Component Analysis helper to check out eigenvalues of components. **Args:** * `x` : input matrix (2d array), every row represents new sample **Returns:** * `components`: sorted array of principal components eigenvalues """ # validate inputs try: x = np.array(x) except: raise ValueError('Impossible to convert x to a numpy array.') # eigen values and eigen vectors of data covariance matrix eigen_values, eigen_vectors = np.linalg.eig(np.cov(x.T)) # sort eigen vectors according biggest eigen value eigen_order = eigen_vectors.T[(-eigen_values).argsort()] # form output - order the eigenvalues return eigen_values[(-eigen_values).argsort()]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:add_mpl_colorbar; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, identifier:dfr; 5, identifier:fig; 6, identifier:dend; 7, identifier:params; 8, default_parameter; 8, 9; 8, 10; 9, identifier:orientation; 10, string:"row"; 11, block; 11, 12; 11, 14; 11, 41; 11, 42; 11, 63; 11, 64; 11, 68; 11, 107; 11, 116; 11, 117; 11, 212; 11, 217; 12, expression_statement; 12, 13; 13, comment; 14, for_statement; 14, 15; 14, 16; 14, 25; 15, identifier:name; 16, subscript; 16, 17; 16, 20; 17, attribute; 17, 18; 17, 19; 18, identifier:dfr; 19, identifier:index; 20, subscript; 20, 21; 20, 24; 21, subscript; 21, 22; 21, 23; 22, identifier:dend; 23, string:"dendrogram"; 24, string:"leaves"; 25, block; 25, 26; 26, if_statement; 26, 27; 26, 32; 27, comparison_operator:not; 27, 28; 27, 29; 28, identifier:name; 29, attribute; 29, 30; 29, 31; 30, identifier:params; 31, identifier:classes; 32, block; 32, 33; 33, expression_statement; 33, 34; 34, assignment; 34, 35; 34, 40; 35, subscript; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:params; 38, identifier:classes; 39, identifier:name; 40, identifier:name; 41, comment; 42, expression_statement; 42, 43; 43, assignment; 43, 44; 43, 45; 44, identifier:classdict; 45, dictionary_comprehension; 45, 46; 45, 49; 46, pair; 46, 47; 46, 48; 47, identifier:cls; 48, identifier:idx; 49, for_in_clause; 49, 50; 49, 53; 50, tuple_pattern; 50, 51; 50, 52; 51, identifier:idx; 52, identifier:cls; 53, call; 53, 54; 53, 55; 54, identifier:enumerate; 55, argument_list; 55, 56; 56, call; 56, 57; 56, 62; 57, attribute; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:params; 60, identifier:classes; 61, identifier:values; 62, argument_list; 63, comment; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:cblist; 67, list:[]; 68, for_statement; 68, 69; 68, 70; 68, 79; 69, identifier:name; 70, subscript; 70, 71; 70, 74; 71, attribute; 71, 72; 71, 73; 72, identifier:dfr; 73, identifier:index; 74, subscript; 74, 75; 74, 78; 75, subscript; 75, 76; 75, 77; 76, identifier:dend; 77, string:"dendrogram"; 78, string:"leaves"; 79, block; 79, 80; 80, try_statement; 80, 81; 80, 95; 81, block; 81, 82; 82, expression_statement; 82, 83; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:cblist; 86, identifier:append; 87, argument_list; 87, 88; 88, subscript; 88, 89; 88, 90; 89, identifier:classdict; 90, subscript; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:params; 93, identifier:classes; 94, identifier:name; 95, except_clause; 95, 96; 95, 97; 96, identifier:KeyError; 97, block; 97, 98; 98, expression_statement; 98, 99; 99, call; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:cblist; 102, identifier:append; 103, argument_list; 103, 104; 104, subscript; 104, 105; 104, 106; 105, identifier:classdict; 106, identifier:name; 107, expression_statement; 107, 108; 108, assignment; 108, 109; 108, 110; 109, identifier:colbar; 110, call; 110, 111; 110, 114; 111, attribute; 111, 112; 111, 113; 112, identifier:pd; 113, identifier:Series; 114, argument_list; 114, 115; 115, identifier:cblist; 116, comment; 117, if_statement; 117, 118; 117, 121; 117, 169; 118, comparison_operator:==; 118, 119; 118, 120; 119, identifier:orientation; 120, string:"row"; 121, block; 121, 122; 121, 136; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:cbaxes; 125, call; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:fig; 128, identifier:add_subplot; 129, argument_list; 129, 130; 130, subscript; 130, 131; 130, 134; 130, 135; 131, subscript; 131, 132; 131, 133; 132, identifier:dend; 133, string:"gridspec"; 134, integer:0; 135, integer:1; 136, expression_statement; 136, 137; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:cbaxes; 140, identifier:imshow; 141, argument_list; 141, 142; 141, 150; 141, 160; 141, 163; 141, 166; 142, list_comprehension; 142, 143; 142, 145; 143, list:[cbar]; 143, 144; 144, identifier:cbar; 145, for_in_clause; 145, 146; 145, 147; 146, identifier:cbar; 147, attribute; 147, 148; 147, 149; 148, identifier:colbar; 149, identifier:values; 150, keyword_argument; 150, 151; 150, 152; 151, identifier:cmap; 152, call; 152, 153; 152, 156; 153, attribute; 153, 154; 153, 155; 154, identifier:plt; 155, identifier:get_cmap; 156, argument_list; 156, 157; 157, attribute; 157, 158; 157, 159; 158, identifier:pyani_config; 159, identifier:MPL_CBAR; 160, keyword_argument; 160, 161; 160, 162; 161, identifier:interpolation; 162, string:"nearest"; 163, keyword_argument; 163, 164; 163, 165; 164, identifier:aspect; 165, string:"auto"; 166, keyword_argument; 166, 167; 166, 168; 167, identifier:origin; 168, string:"lower"; 169, else_clause; 169, 170; 170, block; 170, 171; 170, 185; 171, expression_statement; 171, 172; 172, assignment; 172, 173; 172, 174; 173, identifier:cbaxes; 174, call; 174, 175; 174, 178; 175, attribute; 175, 176; 175, 177; 176, identifier:fig; 177, identifier:add_subplot; 178, argument_list; 178, 179; 179, subscript; 179, 180; 179, 183; 179, 184; 180, subscript; 180, 181; 180, 182; 181, identifier:dend; 182, string:"gridspec"; 183, integer:1; 184, integer:0; 185, expression_statement; 185, 186; 186, call; 186, 187; 186, 190; 187, attribute; 187, 188; 187, 189; 188, identifier:cbaxes; 189, identifier:imshow; 190, argument_list; 190, 191; 190, 193; 190, 203; 190, 206; 190, 209; 191, list:[colbar]; 191, 192; 192, identifier:colbar; 193, keyword_argument; 193, 194; 193, 195; 194, identifier:cmap; 195, call; 195, 196; 195, 199; 196, attribute; 196, 197; 196, 198; 197, identifier:plt; 198, identifier:get_cmap; 199, argument_list; 199, 200; 200, attribute; 200, 201; 200, 202; 201, identifier:pyani_config; 202, identifier:MPL_CBAR; 203, keyword_argument; 203, 204; 203, 205; 204, identifier:interpolation; 205, string:"nearest"; 206, keyword_argument; 206, 207; 206, 208; 207, identifier:aspect; 208, string:"auto"; 209, keyword_argument; 209, 210; 209, 211; 210, identifier:origin; 211, string:"lower"; 212, expression_statement; 212, 213; 213, call; 213, 214; 213, 215; 214, identifier:clean_axis; 215, argument_list; 215, 216; 216, identifier:cbaxes; 217, return_statement; 217, 218; 218, identifier:colbar
def add_mpl_colorbar(dfr, fig, dend, params, orientation="row"): """Add class colorbars to Matplotlib heatmap.""" for name in dfr.index[dend["dendrogram"]["leaves"]]: if name not in params.classes: params.classes[name] = name # Assign a numerical value to each class, for mpl classdict = {cls: idx for (idx, cls) in enumerate(params.classes.values())} # colourbar cblist = [] for name in dfr.index[dend["dendrogram"]["leaves"]]: try: cblist.append(classdict[params.classes[name]]) except KeyError: cblist.append(classdict[name]) colbar = pd.Series(cblist) # Create colourbar axis - could capture if needed if orientation == "row": cbaxes = fig.add_subplot(dend["gridspec"][0, 1]) cbaxes.imshow( [[cbar] for cbar in colbar.values], cmap=plt.get_cmap(pyani_config.MPL_CBAR), interpolation="nearest", aspect="auto", origin="lower", ) else: cbaxes = fig.add_subplot(dend["gridspec"][1, 0]) cbaxes.imshow( [colbar], cmap=plt.get_cmap(pyani_config.MPL_CBAR), interpolation="nearest", aspect="auto", origin="lower", ) clean_axis(cbaxes) return colbar
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:calculate_anim; 3, parameters; 3, 4; 3, 5; 4, identifier:infiles; 5, identifier:org_lengths; 6, block; 6, 7; 6, 9; 6, 16; 6, 23; 6, 39; 6, 47; 6, 48; 6, 229; 6, 230; 6, 237; 6, 250; 6, 322; 6, 341; 6, 342; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, call; 10, 11; 10, 14; 11, attribute; 11, 12; 11, 13; 12, identifier:logger; 13, identifier:info; 14, argument_list; 14, 15; 15, string:"Running ANIm"; 16, expression_statement; 16, 17; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:logger; 20, identifier:info; 21, argument_list; 21, 22; 22, string:"Generating NUCmer command-lines"; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:deltadir; 26, call; 26, 27; 26, 32; 27, attribute; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:os; 30, identifier:path; 31, identifier:join; 32, argument_list; 32, 33; 32, 36; 33, attribute; 33, 34; 33, 35; 34, identifier:args; 35, identifier:outdirname; 36, subscript; 36, 37; 36, 38; 37, identifier:ALIGNDIR; 38, string:"ANIm"; 39, expression_statement; 39, 40; 40, call; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:logger; 43, identifier:info; 44, argument_list; 44, 45; 44, 46; 45, string:"Writing nucmer output to %s"; 46, identifier:deltadir; 47, comment; 48, if_statement; 48, 49; 48, 53; 48, 220; 49, not_operator; 49, 50; 50, attribute; 50, 51; 50, 52; 51, identifier:args; 52, identifier:skip_nucmer; 53, block; 53, 54; 53, 86; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:joblist; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:anim; 60, identifier:generate_nucmer_jobs; 61, argument_list; 61, 62; 61, 63; 61, 66; 61, 71; 61, 76; 61, 81; 62, identifier:infiles; 63, attribute; 63, 64; 63, 65; 64, identifier:args; 65, identifier:outdirname; 66, keyword_argument; 66, 67; 66, 68; 67, identifier:nucmer_exe; 68, attribute; 68, 69; 68, 70; 69, identifier:args; 70, identifier:nucmer_exe; 71, keyword_argument; 71, 72; 71, 73; 72, identifier:filter_exe; 73, attribute; 73, 74; 73, 75; 74, identifier:args; 75, identifier:filter_exe; 76, keyword_argument; 76, 77; 76, 78; 77, identifier:maxmatch; 78, attribute; 78, 79; 78, 80; 79, identifier:args; 80, identifier:maxmatch; 81, keyword_argument; 81, 82; 81, 83; 82, identifier:jobprefix; 83, attribute; 83, 84; 83, 85; 84, identifier:args; 85, identifier:jobprefix; 86, if_statement; 86, 87; 86, 92; 86, 176; 87, comparison_operator:==; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:args; 90, identifier:scheduler; 91, string:"multiprocessing"; 92, block; 92, 93; 92, 100; 92, 128; 92, 145; 92, 153; 93, expression_statement; 93, 94; 94, call; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:logger; 97, identifier:info; 98, argument_list; 98, 99; 99, string:"Running jobs with multiprocessing"; 100, if_statement; 100, 101; 100, 106; 100, 116; 101, comparison_operator:is; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:args; 104, identifier:workers; 105, None; 106, block; 106, 107; 107, expression_statement; 107, 108; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:logger; 111, identifier:info; 112, argument_list; 112, 113; 113, binary_operator:+; 113, 114; 113, 115; 114, string:"(using maximum number of available "; 115, string:"worker threads)"; 116, else_clause; 116, 117; 117, block; 117, 118; 118, expression_statement; 118, 119; 119, call; 119, 120; 119, 123; 120, attribute; 120, 121; 120, 122; 121, identifier:logger; 122, identifier:info; 123, argument_list; 123, 124; 123, 125; 124, string:"(using %d worker threads, if available)"; 125, attribute; 125, 126; 125, 127; 126, identifier:args; 127, identifier:workers; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 131; 130, identifier:cumval; 131, call; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:run_mp; 134, identifier:run_dependency_graph; 135, argument_list; 135, 136; 135, 137; 135, 142; 136, identifier:joblist; 137, keyword_argument; 137, 138; 137, 139; 138, identifier:workers; 139, attribute; 139, 140; 139, 141; 140, identifier:args; 141, identifier:workers; 142, keyword_argument; 142, 143; 142, 144; 143, identifier:logger; 144, identifier:logger; 145, expression_statement; 145, 146; 146, call; 146, 147; 146, 150; 147, attribute; 147, 148; 147, 149; 148, identifier:logger; 149, identifier:info; 150, argument_list; 150, 151; 150, 152; 151, string:"Cumulative return value: %d"; 152, identifier:cumval; 153, if_statement; 153, 154; 153, 157; 153, 167; 154, comparison_operator:<; 154, 155; 154, 156; 155, integer:0; 156, identifier:cumval; 157, block; 157, 158; 158, expression_statement; 158, 159; 159, call; 159, 160; 159, 163; 160, attribute; 160, 161; 160, 162; 161, identifier:logger; 162, identifier:warning; 163, argument_list; 163, 164; 164, binary_operator:+; 164, 165; 164, 166; 165, string:"At least one NUCmer comparison failed. "; 166, string:"ANIm may fail."; 167, else_clause; 167, 168; 168, block; 168, 169; 169, expression_statement; 169, 170; 170, call; 170, 171; 170, 174; 171, attribute; 171, 172; 171, 173; 172, identifier:logger; 173, identifier:info; 174, argument_list; 174, 175; 175, string:"All multiprocessing jobs complete."; 176, else_clause; 176, 177; 177, block; 177, 178; 177, 185; 177, 195; 178, expression_statement; 178, 179; 179, call; 179, 180; 179, 183; 180, attribute; 180, 181; 180, 182; 181, identifier:logger; 182, identifier:info; 183, argument_list; 183, 184; 184, string:"Running jobs with SGE"; 185, expression_statement; 185, 186; 186, call; 186, 187; 186, 190; 187, attribute; 187, 188; 187, 189; 188, identifier:logger; 189, identifier:info; 190, argument_list; 190, 191; 190, 192; 191, string:"Jobarray group size set to %d"; 192, attribute; 192, 193; 192, 194; 193, identifier:args; 194, identifier:sgegroupsize; 195, expression_statement; 195, 196; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:run_sge; 199, identifier:run_dependency_graph; 200, argument_list; 200, 201; 200, 202; 200, 205; 200, 210; 200, 215; 201, identifier:joblist; 202, keyword_argument; 202, 203; 202, 204; 203, identifier:logger; 204, identifier:logger; 205, keyword_argument; 205, 206; 205, 207; 206, identifier:jgprefix; 207, attribute; 207, 208; 207, 209; 208, identifier:args; 209, identifier:jobprefix; 210, keyword_argument; 210, 211; 210, 212; 211, identifier:sgegroupsize; 212, attribute; 212, 213; 212, 214; 213, identifier:args; 214, identifier:sgegroupsize; 215, keyword_argument; 215, 216; 215, 217; 216, identifier:sgeargs; 217, attribute; 217, 218; 217, 219; 218, identifier:args; 219, identifier:sgeargs; 220, else_clause; 220, 221; 221, block; 221, 222; 222, expression_statement; 222, 223; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:logger; 226, identifier:warning; 227, argument_list; 227, 228; 228, string:"Skipping NUCmer run (as instructed)!"; 229, comment; 230, expression_statement; 230, 231; 231, call; 231, 232; 231, 235; 232, attribute; 232, 233; 232, 234; 233, identifier:logger; 234, identifier:info; 235, argument_list; 235, 236; 236, string:"Processing NUCmer .delta files."; 237, expression_statement; 237, 238; 238, assignment; 238, 239; 238, 240; 239, identifier:results; 240, call; 240, 241; 240, 244; 241, attribute; 241, 242; 241, 243; 242, identifier:anim; 243, identifier:process_deltadir; 244, argument_list; 244, 245; 244, 246; 244, 247; 245, identifier:deltadir; 246, identifier:org_lengths; 247, keyword_argument; 247, 248; 247, 249; 248, identifier:logger; 249, identifier:logger; 250, if_statement; 250, 251; 250, 254; 250, 255; 251, attribute; 251, 252; 251, 253; 252, identifier:results; 253, identifier:zero_error; 254, comment; 255, block; 255, 256; 256, if_statement; 256, 257; 256, 267; 257, boolean_operator:and; 257, 258; 257, 262; 258, not_operator; 258, 259; 259, attribute; 259, 260; 259, 261; 260, identifier:args; 261, identifier:skip_nucmer; 262, comparison_operator:==; 262, 263; 262, 266; 263, attribute; 263, 264; 263, 265; 264, identifier:args; 265, identifier:scheduler; 266, string:"multiprocessing"; 267, block; 267, 268; 268, if_statement; 268, 269; 268, 272; 268, 298; 269, comparison_operator:<; 269, 270; 269, 271; 270, integer:0; 271, identifier:cumval; 272, block; 272, 273; 272, 282; 272, 291; 273, expression_statement; 273, 274; 274, call; 274, 275; 274, 278; 275, attribute; 275, 276; 275, 277; 276, identifier:logger; 277, identifier:error; 278, argument_list; 278, 279; 279, binary_operator:+; 279, 280; 279, 281; 280, string:"This has possibly been a NUCmer run failure, "; 281, string:"please investigate"; 282, expression_statement; 282, 283; 283, call; 283, 284; 283, 287; 284, attribute; 284, 285; 284, 286; 285, identifier:logger; 286, identifier:error; 287, argument_list; 287, 288; 288, call; 288, 289; 288, 290; 289, identifier:last_exception; 290, argument_list; 291, expression_statement; 291, 292; 292, call; 292, 293; 292, 296; 293, attribute; 293, 294; 293, 295; 294, identifier:sys; 295, identifier:exit; 296, argument_list; 296, 297; 297, integer:1; 298, else_clause; 298, 299; 299, block; 299, 300; 299, 311; 300, expression_statement; 300, 301; 301, call; 301, 302; 301, 305; 302, attribute; 302, 303; 302, 304; 303, identifier:logger; 304, identifier:error; 305, argument_list; 305, 306; 306, binary_operator:+; 306, 307; 306, 310; 307, binary_operator:+; 307, 308; 307, 309; 308, string:"This is possibly due to a NUCmer comparison "; 309, string:"being too distant for use. Please consider "; 310, string:"using the --maxmatch option."; 311, expression_statement; 311, 312; 312, call; 312, 313; 312, 316; 313, attribute; 313, 314; 313, 315; 314, identifier:logger; 315, identifier:error; 316, argument_list; 316, 317; 317, binary_operator:+; 317, 318; 317, 321; 318, binary_operator:+; 318, 319; 318, 320; 319, string:"This is alternatively due to NUCmer run "; 320, string:"failure, analysis will continue, but please "; 321, string:"investigate."; 322, if_statement; 322, 323; 322, 327; 323, not_operator; 323, 324; 324, attribute; 324, 325; 324, 326; 325, identifier:args; 326, identifier:nocompress; 327, block; 327, 328; 327, 336; 328, expression_statement; 328, 329; 329, call; 329, 330; 329, 333; 330, attribute; 330, 331; 330, 332; 331, identifier:logger; 332, identifier:info; 333, argument_list; 333, 334; 333, 335; 334, string:"Compressing/deleting %s"; 335, identifier:deltadir; 336, expression_statement; 336, 337; 337, call; 337, 338; 337, 339; 338, identifier:compress_delete_outdir; 339, argument_list; 339, 340; 340, identifier:deltadir; 341, comment; 342, return_statement; 342, 343; 343, identifier:results
def calculate_anim(infiles, org_lengths): """Returns ANIm result dataframes for files in input directory. - infiles - paths to each input file - org_lengths - dictionary of input sequence lengths, keyed by sequence Finds ANI by the ANIm method, as described in Richter et al (2009) Proc Natl Acad Sci USA 106: 19126-19131 doi:10.1073/pnas.0906412106. All FASTA format files (selected by suffix) in the input directory are compared against each other, pairwise, using NUCmer (which must be in the path). NUCmer output is stored in the output directory. The NUCmer .delta file output is parsed to obtain an alignment length and similarity error count for every unique region alignment between the two organisms, as represented by the sequences in the FASTA files. These are processed to give matrices of aligned sequence lengths, average nucleotide identity (ANI) percentages, coverage (aligned percentage of whole genome), and similarity error cound for each pairwise comparison. """ logger.info("Running ANIm") logger.info("Generating NUCmer command-lines") deltadir = os.path.join(args.outdirname, ALIGNDIR["ANIm"]) logger.info("Writing nucmer output to %s", deltadir) # Schedule NUCmer runs if not args.skip_nucmer: joblist = anim.generate_nucmer_jobs( infiles, args.outdirname, nucmer_exe=args.nucmer_exe, filter_exe=args.filter_exe, maxmatch=args.maxmatch, jobprefix=args.jobprefix, ) if args.scheduler == "multiprocessing": logger.info("Running jobs with multiprocessing") if args.workers is None: logger.info("(using maximum number of available " + "worker threads)") else: logger.info("(using %d worker threads, if available)", args.workers) cumval = run_mp.run_dependency_graph( joblist, workers=args.workers, logger=logger ) logger.info("Cumulative return value: %d", cumval) if 0 < cumval: logger.warning( "At least one NUCmer comparison failed. " + "ANIm may fail." ) else: logger.info("All multiprocessing jobs complete.") else: logger.info("Running jobs with SGE") logger.info("Jobarray group size set to %d", args.sgegroupsize) run_sge.run_dependency_graph( joblist, logger=logger, jgprefix=args.jobprefix, sgegroupsize=args.sgegroupsize, sgeargs=args.sgeargs, ) else: logger.warning("Skipping NUCmer run (as instructed)!") # Process resulting .delta files logger.info("Processing NUCmer .delta files.") results = anim.process_deltadir(deltadir, org_lengths, logger=logger) if results.zero_error: # zero percentage identity error if not args.skip_nucmer and args.scheduler == "multiprocessing": if 0 < cumval: logger.error( "This has possibly been a NUCmer run failure, " + "please investigate" ) logger.error(last_exception()) sys.exit(1) else: logger.error( "This is possibly due to a NUCmer comparison " + "being too distant for use. Please consider " + "using the --maxmatch option." ) logger.error( "This is alternatively due to NUCmer run " + "failure, analysis will continue, but please " + "investigate." ) if not args.nocompress: logger.info("Compressing/deleting %s", deltadir) compress_delete_outdir(deltadir) # Return processed data from .delta files return results
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:unified_anib; 3, parameters; 3, 4; 3, 5; 4, identifier:infiles; 5, identifier:org_lengths; 6, block; 6, 7; 6, 9; 6, 19; 6, 37; 6, 45; 6, 46; 6, 308; 6, 309; 6, 319; 6, 389; 6, 408; 6, 409; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, call; 10, 11; 10, 14; 11, attribute; 11, 12; 11, 13; 12, identifier:logger; 13, identifier:info; 14, argument_list; 14, 15; 14, 16; 15, string:"Running %s"; 16, attribute; 16, 17; 16, 18; 17, identifier:args; 18, identifier:method; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:blastdir; 22, call; 22, 23; 22, 28; 23, attribute; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:os; 26, identifier:path; 27, identifier:join; 28, argument_list; 28, 29; 28, 32; 29, attribute; 29, 30; 29, 31; 30, identifier:args; 31, identifier:outdirname; 32, subscript; 32, 33; 32, 34; 33, identifier:ALIGNDIR; 34, attribute; 34, 35; 34, 36; 35, identifier:args; 36, identifier:method; 37, expression_statement; 37, 38; 38, call; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:logger; 41, identifier:info; 42, argument_list; 42, 43; 42, 44; 43, string:"Writing BLAST output to %s"; 44, identifier:blastdir; 45, comment; 46, if_statement; 46, 47; 46, 51; 46, 52; 46, 256; 47, not_operator; 47, 48; 48, attribute; 48, 49; 48, 50; 49, identifier:args; 50, identifier:skip_blastn; 51, comment; 52, block; 52, 53; 52, 63; 52, 64; 52, 79; 52, 80; 52, 108; 52, 109; 52, 110; 52, 111; 52, 112; 52, 113; 52, 114; 52, 115; 52, 116; 52, 123; 52, 142; 52, 143; 52, 144; 52, 145; 53, expression_statement; 53, 54; 54, call; 54, 55; 54, 58; 55, attribute; 55, 56; 55, 57; 56, identifier:logger; 57, identifier:info; 58, argument_list; 58, 59; 58, 60; 59, string:"Fragmenting input files, and writing to %s"; 60, attribute; 60, 61; 60, 62; 61, identifier:args; 62, identifier:outdirname; 63, comment; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 69; 66, pattern_list; 66, 67; 66, 68; 67, identifier:fragfiles; 68, identifier:fraglengths; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:anib; 72, identifier:fragment_fasta_files; 73, argument_list; 73, 74; 73, 75; 73, 76; 74, identifier:infiles; 75, identifier:blastdir; 76, attribute; 76, 77; 76, 78; 77, identifier:args; 78, identifier:fragsize; 79, comment; 80, with_statement; 80, 81; 80, 99; 81, with_clause; 81, 82; 82, with_item; 82, 83; 83, as_pattern; 83, 84; 83, 97; 84, call; 84, 85; 84, 86; 85, identifier:open; 86, argument_list; 86, 87; 86, 96; 87, call; 87, 88; 87, 93; 88, attribute; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:os; 91, identifier:path; 92, identifier:join; 93, argument_list; 93, 94; 93, 95; 94, identifier:blastdir; 95, string:"fraglengths.json"; 96, string:"w"; 97, as_pattern_target; 97, 98; 98, identifier:outfile; 99, block; 99, 100; 100, expression_statement; 100, 101; 101, call; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:json; 104, identifier:dump; 105, argument_list; 105, 106; 105, 107; 106, identifier:fraglengths; 107, identifier:outfile; 108, comment; 109, comment; 110, comment; 111, comment; 112, comment; 113, comment; 114, comment; 115, comment; 116, expression_statement; 116, 117; 117, call; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:logger; 120, identifier:info; 121, argument_list; 121, 122; 122, string:"Creating job dependency graph"; 123, expression_statement; 123, 124; 124, assignment; 124, 125; 124, 126; 125, identifier:jobgraph; 126, call; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:anib; 129, identifier:make_job_graph; 130, argument_list; 130, 131; 130, 132; 130, 133; 131, identifier:infiles; 132, identifier:fragfiles; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:anib; 136, identifier:make_blastcmd_builder; 137, argument_list; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:args; 140, identifier:method; 141, identifier:blastdir; 142, comment; 143, comment; 144, comment; 145, if_statement; 145, 146; 145, 151; 145, 237; 146, comparison_operator:==; 146, 147; 146, 150; 147, attribute; 147, 148; 147, 149; 148, identifier:args; 149, identifier:scheduler; 150, string:"multiprocessing"; 151, block; 151, 152; 151, 159; 151, 166; 151, 194; 151, 211; 152, expression_statement; 152, 153; 153, call; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:logger; 156, identifier:info; 157, argument_list; 157, 158; 158, string:"Running jobs with multiprocessing"; 159, expression_statement; 159, 160; 160, call; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:logger; 163, identifier:info; 164, argument_list; 164, 165; 165, string:"Running job dependency graph"; 166, if_statement; 166, 167; 166, 172; 166, 182; 167, comparison_operator:is; 167, 168; 167, 171; 168, attribute; 168, 169; 168, 170; 169, identifier:args; 170, identifier:workers; 171, None; 172, block; 172, 173; 173, expression_statement; 173, 174; 174, call; 174, 175; 174, 178; 175, attribute; 175, 176; 175, 177; 176, identifier:logger; 177, identifier:info; 178, argument_list; 178, 179; 179, binary_operator:+; 179, 180; 179, 181; 180, string:"(using maximum number of available "; 181, string:"worker threads)"; 182, else_clause; 182, 183; 183, block; 183, 184; 184, expression_statement; 184, 185; 185, call; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:logger; 188, identifier:info; 189, argument_list; 189, 190; 189, 191; 190, string:"(using %d worker threads, if available)"; 191, attribute; 191, 192; 191, 193; 192, identifier:args; 193, identifier:workers; 194, expression_statement; 194, 195; 195, assignment; 195, 196; 195, 197; 196, identifier:cumval; 197, call; 197, 198; 197, 201; 198, attribute; 198, 199; 198, 200; 199, identifier:run_mp; 200, identifier:run_dependency_graph; 201, argument_list; 201, 202; 201, 203; 201, 208; 202, identifier:jobgraph; 203, keyword_argument; 203, 204; 203, 205; 204, identifier:workers; 205, attribute; 205, 206; 205, 207; 206, identifier:args; 207, identifier:workers; 208, keyword_argument; 208, 209; 208, 210; 209, identifier:logger; 210, identifier:logger; 211, if_statement; 211, 212; 211, 215; 211, 228; 212, comparison_operator:<; 212, 213; 212, 214; 213, integer:0; 214, identifier:cumval; 215, block; 215, 216; 216, expression_statement; 216, 217; 217, call; 217, 218; 217, 221; 218, attribute; 218, 219; 218, 220; 219, identifier:logger; 220, identifier:warning; 221, argument_list; 221, 222; 221, 225; 222, binary_operator:+; 222, 223; 222, 224; 223, string:"At least one BLAST run failed. "; 224, string:"%s may fail."; 225, attribute; 225, 226; 225, 227; 226, identifier:args; 227, identifier:method; 228, else_clause; 228, 229; 229, block; 229, 230; 230, expression_statement; 230, 231; 231, call; 231, 232; 231, 235; 232, attribute; 232, 233; 232, 234; 233, identifier:logger; 234, identifier:info; 235, argument_list; 235, 236; 236, string:"All multiprocessing jobs complete."; 237, else_clause; 237, 238; 238, block; 238, 239; 238, 249; 239, expression_statement; 239, 240; 240, call; 240, 241; 240, 244; 241, attribute; 241, 242; 241, 243; 242, identifier:run_sge; 243, identifier:run_dependency_graph; 244, argument_list; 244, 245; 244, 246; 245, identifier:jobgraph; 246, keyword_argument; 246, 247; 246, 248; 247, identifier:logger; 248, identifier:logger; 249, expression_statement; 249, 250; 250, call; 250, 251; 250, 254; 251, attribute; 251, 252; 251, 253; 252, identifier:logger; 253, identifier:info; 254, argument_list; 254, 255; 255, string:"Running jobs with SGE"; 256, else_clause; 256, 257; 256, 258; 257, comment; 258, block; 258, 259; 258, 301; 259, if_statement; 259, 260; 259, 265; 259, 295; 260, comparison_operator:==; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, identifier:args; 263, identifier:method; 264, string:"ANIblastall"; 265, block; 265, 266; 266, with_statement; 266, 267; 266, 285; 267, with_clause; 267, 268; 268, with_item; 268, 269; 269, as_pattern; 269, 270; 269, 283; 270, call; 270, 271; 270, 272; 271, identifier:open; 272, argument_list; 272, 273; 272, 282; 273, call; 273, 274; 273, 279; 274, attribute; 274, 275; 274, 278; 275, attribute; 275, 276; 275, 277; 276, identifier:os; 277, identifier:path; 278, identifier:join; 279, argument_list; 279, 280; 279, 281; 280, identifier:blastdir; 281, string:"fraglengths.json"; 282, string:"rU"; 283, as_pattern_target; 283, 284; 284, identifier:infile; 285, block; 285, 286; 286, expression_statement; 286, 287; 287, assignment; 287, 288; 287, 289; 288, identifier:fraglengths; 289, call; 289, 290; 289, 293; 290, attribute; 290, 291; 290, 292; 291, identifier:json; 292, identifier:load; 293, argument_list; 293, 294; 294, identifier:infile; 295, else_clause; 295, 296; 296, block; 296, 297; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 300; 299, identifier:fraglengths; 300, None; 301, expression_statement; 301, 302; 302, call; 302, 303; 302, 306; 303, attribute; 303, 304; 303, 305; 304, identifier:logger; 305, identifier:warning; 306, argument_list; 306, 307; 307, string:"Skipping BLASTN runs (as instructed)!"; 308, comment; 309, expression_statement; 309, 310; 310, call; 310, 311; 310, 314; 311, attribute; 311, 312; 311, 313; 312, identifier:logger; 313, identifier:info; 314, argument_list; 314, 315; 314, 316; 315, string:"Processing pairwise %s BLAST output."; 316, attribute; 316, 317; 316, 318; 317, identifier:args; 318, identifier:method; 319, try_statement; 319, 320; 319, 339; 320, block; 320, 321; 321, expression_statement; 321, 322; 322, assignment; 322, 323; 322, 324; 323, identifier:data; 324, call; 324, 325; 324, 328; 325, attribute; 325, 326; 325, 327; 326, identifier:anib; 327, identifier:process_blast; 328, argument_list; 328, 329; 328, 330; 328, 331; 328, 334; 329, identifier:blastdir; 330, identifier:org_lengths; 331, keyword_argument; 331, 332; 331, 333; 332, identifier:fraglengths; 333, identifier:fraglengths; 334, keyword_argument; 334, 335; 334, 336; 335, identifier:mode; 336, attribute; 336, 337; 336, 338; 337, identifier:args; 338, identifier:method; 339, except_clause; 339, 340; 339, 341; 340, identifier:ZeroDivisionError; 341, block; 341, 342; 341, 349; 341, 380; 342, expression_statement; 342, 343; 343, call; 343, 344; 343, 347; 344, attribute; 344, 345; 344, 346; 345, identifier:logger; 346, identifier:error; 347, argument_list; 347, 348; 348, string:"One or more BLAST output files has a problem."; 349, if_statement; 349, 350; 349, 354; 350, not_operator; 350, 351; 351, attribute; 351, 352; 351, 353; 352, identifier:args; 353, identifier:skip_blastn; 354, block; 354, 355; 355, if_statement; 355, 356; 355, 359; 355, 369; 356, comparison_operator:<; 356, 357; 356, 358; 357, integer:0; 358, identifier:cumval; 359, block; 359, 360; 360, expression_statement; 360, 361; 361, call; 361, 362; 361, 365; 362, attribute; 362, 363; 362, 364; 363, identifier:logger; 364, identifier:error; 365, argument_list; 365, 366; 366, binary_operator:+; 366, 367; 366, 368; 367, string:"This is possibly due to BLASTN run failure, "; 368, string:"please investigate"; 369, else_clause; 369, 370; 370, block; 370, 371; 371, expression_statement; 371, 372; 372, call; 372, 373; 372, 376; 373, attribute; 373, 374; 373, 375; 374, identifier:logger; 375, identifier:error; 376, argument_list; 376, 377; 377, binary_operator:+; 377, 378; 377, 379; 378, string:"This is possibly due to a BLASTN comparison "; 379, string:"being too distant for use."; 380, expression_statement; 380, 381; 381, call; 381, 382; 381, 385; 382, attribute; 382, 383; 382, 384; 383, identifier:logger; 384, identifier:error; 385, argument_list; 385, 386; 386, call; 386, 387; 386, 388; 387, identifier:last_exception; 388, argument_list; 389, if_statement; 389, 390; 389, 394; 390, not_operator; 390, 391; 391, attribute; 391, 392; 391, 393; 392, identifier:args; 393, identifier:nocompress; 394, block; 394, 395; 394, 403; 395, expression_statement; 395, 396; 396, call; 396, 397; 396, 400; 397, attribute; 397, 398; 397, 399; 398, identifier:logger; 399, identifier:info; 400, argument_list; 400, 401; 400, 402; 401, string:"Compressing/deleting %s"; 402, identifier:blastdir; 403, expression_statement; 403, 404; 404, call; 404, 405; 404, 406; 405, identifier:compress_delete_outdir; 406, argument_list; 406, 407; 407, identifier:blastdir; 408, comment; 409, return_statement; 409, 410; 410, identifier:data
def unified_anib(infiles, org_lengths): """Calculate ANIb for files in input directory. - infiles - paths to each input file - org_lengths - dictionary of input sequence lengths, keyed by sequence Calculates ANI by the ANIb method, as described in Goris et al. (2007) Int J Syst Evol Micr 57: 81-91. doi:10.1099/ijs.0.64483-0. There are some minor differences depending on whether BLAST+ or legacy BLAST (BLASTALL) methods are used. All FASTA format files (selected by suffix) in the input directory are used to construct BLAST databases, placed in the output directory. Each file's contents are also split into sequence fragments of length options.fragsize, and the multiple FASTA file that results written to the output directory. These are BLASTNed, pairwise, against the databases. The BLAST output is interrogated for all fragment matches that cover at least 70% of the query sequence, with at least 30% nucleotide identity over the full length of the query sequence. This is an odd choice and doesn't correspond to the twilight zone limit as implied by Goris et al. We persist with their definition, however. Only these qualifying matches contribute to the total aligned length, and total aligned sequence identity used to calculate ANI. The results are processed to give matrices of aligned sequence length (aln_lengths.tab), similarity error counts (sim_errors.tab), ANIs (perc_ids.tab), and minimum aligned percentage (perc_aln.tab) of each genome, for each pairwise comparison. These are written to the output directory in plain text tab-separated format. """ logger.info("Running %s", args.method) blastdir = os.path.join(args.outdirname, ALIGNDIR[args.method]) logger.info("Writing BLAST output to %s", blastdir) # Build BLAST databases and run pairwise BLASTN if not args.skip_blastn: # Make sequence fragments logger.info("Fragmenting input files, and writing to %s", args.outdirname) # Fraglengths does not get reused with BLASTN fragfiles, fraglengths = anib.fragment_fasta_files( infiles, blastdir, args.fragsize ) # Export fragment lengths as JSON, in case we re-run with --skip_blastn with open(os.path.join(blastdir, "fraglengths.json"), "w") as outfile: json.dump(fraglengths, outfile) # Which executables are we using? # if args.method == "ANIblastall": # format_exe = args.formatdb_exe # blast_exe = args.blastall_exe # else: # format_exe = args.makeblastdb_exe # blast_exe = args.blastn_exe # Run BLAST database-building and executables from a jobgraph logger.info("Creating job dependency graph") jobgraph = anib.make_job_graph( infiles, fragfiles, anib.make_blastcmd_builder(args.method, blastdir) ) # jobgraph = anib.make_job_graph(infiles, fragfiles, blastdir, # format_exe, blast_exe, args.method, # jobprefix=args.jobprefix) if args.scheduler == "multiprocessing": logger.info("Running jobs with multiprocessing") logger.info("Running job dependency graph") if args.workers is None: logger.info("(using maximum number of available " + "worker threads)") else: logger.info("(using %d worker threads, if available)", args.workers) cumval = run_mp.run_dependency_graph( jobgraph, workers=args.workers, logger=logger ) if 0 < cumval: logger.warning( "At least one BLAST run failed. " + "%s may fail.", args.method ) else: logger.info("All multiprocessing jobs complete.") else: run_sge.run_dependency_graph(jobgraph, logger=logger) logger.info("Running jobs with SGE") else: # Import fragment lengths from JSON if args.method == "ANIblastall": with open(os.path.join(blastdir, "fraglengths.json"), "rU") as infile: fraglengths = json.load(infile) else: fraglengths = None logger.warning("Skipping BLASTN runs (as instructed)!") # Process pairwise BLASTN output logger.info("Processing pairwise %s BLAST output.", args.method) try: data = anib.process_blast( blastdir, org_lengths, fraglengths=fraglengths, mode=args.method ) except ZeroDivisionError: logger.error("One or more BLAST output files has a problem.") if not args.skip_blastn: if 0 < cumval: logger.error( "This is possibly due to BLASTN run failure, " + "please investigate" ) else: logger.error( "This is possibly due to a BLASTN comparison " + "being too distant for use." ) logger.error(last_exception()) if not args.nocompress: logger.info("Compressing/deleting %s", blastdir) compress_delete_outdir(blastdir) # Return processed BLAST data return data
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:process_deltadir; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:delta_dir; 5, identifier:org_lengths; 6, default_parameter; 6, 7; 6, 8; 7, identifier:logger; 8, None; 9, block; 9, 10; 9, 12; 9, 13; 9, 14; 9, 24; 9, 25; 9, 40; 9, 41; 9, 64; 9, 65; 9, 66; 9, 285; 10, expression_statement; 10, 11; 11, comment; 12, comment; 13, comment; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:deltafiles; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:pyani_files; 20, identifier:get_input_files; 21, argument_list; 21, 22; 21, 23; 22, identifier:delta_dir; 23, string:".filter"; 24, comment; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:results; 28, call; 28, 29; 28, 30; 29, identifier:ANIResults; 30, argument_list; 30, 31; 30, 39; 31, call; 31, 32; 31, 33; 32, identifier:list; 33, argument_list; 33, 34; 34, call; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:org_lengths; 37, identifier:keys; 38, argument_list; 39, string:"ANIm"; 40, comment; 41, for_statement; 41, 42; 41, 45; 41, 53; 42, pattern_list; 42, 43; 42, 44; 43, identifier:org; 44, identifier:length; 45, call; 45, 46; 45, 47; 46, identifier:list; 47, argument_list; 47, 48; 48, call; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:org_lengths; 51, identifier:items; 52, argument_list; 53, block; 53, 54; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 63; 56, subscript; 56, 57; 56, 62; 57, subscript; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:results; 60, identifier:alignment_lengths; 61, identifier:org; 62, identifier:org; 63, identifier:length; 64, comment; 65, comment; 66, for_statement; 66, 67; 66, 68; 66, 69; 67, identifier:deltafile; 68, identifier:deltafiles; 69, block; 69, 70; 69, 100; 69, 101; 69, 102; 69, 131; 69, 160; 69, 169; 69, 192; 69, 203; 69, 214; 69, 215; 69, 216; 69, 217; 69, 218; 69, 219; 69, 246; 69, 247; 69, 248; 69, 257; 69, 266; 69, 275; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 75; 72, pattern_list; 72, 73; 72, 74; 73, identifier:qname; 74, identifier:sname; 75, call; 75, 76; 75, 98; 76, attribute; 76, 77; 76, 97; 77, subscript; 77, 78; 77, 96; 78, call; 78, 79; 78, 84; 79, attribute; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:os; 82, identifier:path; 83, identifier:splitext; 84, argument_list; 84, 85; 85, subscript; 85, 86; 85, 94; 86, call; 86, 87; 86, 92; 87, attribute; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:os; 90, identifier:path; 91, identifier:split; 92, argument_list; 92, 93; 93, identifier:deltafile; 94, unary_operator:-; 94, 95; 95, integer:1; 96, integer:0; 97, identifier:split; 98, argument_list; 98, 99; 99, string:"_vs_"; 100, comment; 101, comment; 102, if_statement; 102, 103; 102, 113; 103, comparison_operator:not; 103, 104; 103, 105; 104, identifier:qname; 105, call; 105, 106; 105, 107; 106, identifier:list; 107, argument_list; 107, 108; 108, call; 108, 109; 108, 112; 109, attribute; 109, 110; 109, 111; 110, identifier:org_lengths; 111, identifier:keys; 112, argument_list; 113, block; 113, 114; 113, 130; 114, if_statement; 114, 115; 114, 116; 115, identifier:logger; 116, block; 116, 117; 117, expression_statement; 117, 118; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:logger; 121, identifier:warning; 122, argument_list; 122, 123; 123, binary_operator:+; 123, 124; 123, 127; 124, binary_operator:%; 124, 125; 124, 126; 125, string:"Query name %s not in input "; 126, identifier:qname; 127, binary_operator:%; 127, 128; 127, 129; 128, string:"sequence list, skipping %s"; 129, identifier:deltafile; 130, continue_statement; 131, if_statement; 131, 132; 131, 142; 132, comparison_operator:not; 132, 133; 132, 134; 133, identifier:sname; 134, call; 134, 135; 134, 136; 135, identifier:list; 136, argument_list; 136, 137; 137, call; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:org_lengths; 140, identifier:keys; 141, argument_list; 142, block; 142, 143; 142, 159; 143, if_statement; 143, 144; 143, 145; 144, identifier:logger; 145, block; 145, 146; 146, expression_statement; 146, 147; 147, call; 147, 148; 147, 151; 148, attribute; 148, 149; 148, 150; 149, identifier:logger; 150, identifier:warning; 151, argument_list; 151, 152; 152, binary_operator:+; 152, 153; 152, 156; 153, binary_operator:%; 153, 154; 153, 155; 154, string:"Subject name %s not in input "; 155, identifier:sname; 156, binary_operator:%; 156, 157; 156, 158; 157, string:"sequence list, skipping %s"; 158, identifier:deltafile; 159, continue_statement; 160, expression_statement; 160, 161; 161, assignment; 161, 162; 161, 165; 162, pattern_list; 162, 163; 162, 164; 163, identifier:tot_length; 164, identifier:tot_sim_error; 165, call; 165, 166; 165, 167; 166, identifier:parse_delta; 167, argument_list; 167, 168; 168, identifier:deltafile; 169, if_statement; 169, 170; 169, 177; 170, boolean_operator:and; 170, 171; 170, 174; 171, comparison_operator:==; 171, 172; 171, 173; 172, identifier:tot_length; 173, integer:0; 174, comparison_operator:is; 174, 175; 174, 176; 175, identifier:logger; 176, None; 177, block; 177, 178; 178, if_statement; 178, 179; 178, 180; 179, identifier:logger; 180, block; 180, 181; 181, expression_statement; 181, 182; 182, call; 182, 183; 182, 186; 183, attribute; 183, 184; 183, 185; 184, identifier:logger; 185, identifier:warning; 186, argument_list; 186, 187; 187, binary_operator:+; 187, 188; 187, 189; 188, string:"Total alignment length reported in "; 189, binary_operator:%; 189, 190; 189, 191; 190, string:"%s is zero!"; 191, identifier:deltafile; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 195; 194, identifier:query_cover; 195, binary_operator:/; 195, 196; 195, 200; 196, call; 196, 197; 196, 198; 197, identifier:float; 198, argument_list; 198, 199; 199, identifier:tot_length; 200, subscript; 200, 201; 200, 202; 201, identifier:org_lengths; 202, identifier:qname; 203, expression_statement; 203, 204; 204, assignment; 204, 205; 204, 206; 205, identifier:sbjct_cover; 206, binary_operator:/; 206, 207; 206, 211; 207, call; 207, 208; 207, 209; 208, identifier:float; 209, argument_list; 209, 210; 210, identifier:tot_length; 211, subscript; 211, 212; 211, 213; 212, identifier:org_lengths; 213, identifier:sname; 214, comment; 215, comment; 216, comment; 217, comment; 218, comment; 219, try_statement; 219, 220; 219, 232; 220, block; 220, 221; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 224; 223, identifier:perc_id; 224, binary_operator:-; 224, 225; 224, 226; 225, integer:1; 226, binary_operator:/; 226, 227; 226, 231; 227, call; 227, 228; 227, 229; 228, identifier:float; 229, argument_list; 229, 230; 230, identifier:tot_sim_error; 231, identifier:tot_length; 232, except_clause; 232, 233; 232, 234; 233, identifier:ZeroDivisionError; 234, block; 234, 235; 234, 239; 234, 240; 235, expression_statement; 235, 236; 236, assignment; 236, 237; 236, 238; 237, identifier:perc_id; 238, integer:0; 239, comment; 240, expression_statement; 240, 241; 241, assignment; 241, 242; 241, 245; 242, attribute; 242, 243; 242, 244; 243, identifier:results; 244, identifier:zero_error; 245, True; 246, comment; 247, comment; 248, expression_statement; 248, 249; 249, call; 249, 250; 249, 253; 250, attribute; 250, 251; 250, 252; 251, identifier:results; 252, identifier:add_tot_length; 253, argument_list; 253, 254; 253, 255; 253, 256; 254, identifier:qname; 255, identifier:sname; 256, identifier:tot_length; 257, expression_statement; 257, 258; 258, call; 258, 259; 258, 262; 259, attribute; 259, 260; 259, 261; 260, identifier:results; 261, identifier:add_sim_errors; 262, argument_list; 262, 263; 262, 264; 262, 265; 263, identifier:qname; 264, identifier:sname; 265, identifier:tot_sim_error; 266, expression_statement; 266, 267; 267, call; 267, 268; 267, 271; 268, attribute; 268, 269; 268, 270; 269, identifier:results; 270, identifier:add_pid; 271, argument_list; 271, 272; 271, 273; 271, 274; 272, identifier:qname; 273, identifier:sname; 274, identifier:perc_id; 275, expression_statement; 275, 276; 276, call; 276, 277; 276, 280; 277, attribute; 277, 278; 277, 279; 278, identifier:results; 279, identifier:add_coverage; 280, argument_list; 280, 281; 280, 282; 280, 283; 280, 284; 281, identifier:qname; 282, identifier:sname; 283, identifier:query_cover; 284, identifier:sbjct_cover; 285, return_statement; 285, 286; 286, identifier:results
def process_deltadir(delta_dir, org_lengths, logger=None): """Returns a tuple of ANIm results for .deltas in passed directory. - delta_dir - path to the directory containing .delta files - org_lengths - dictionary of total sequence lengths, keyed by sequence Returns the following pandas dataframes in an ANIResults object; query sequences are rows, subject sequences are columns: - alignment_lengths - symmetrical: total length of alignment - percentage_identity - symmetrical: percentage identity of alignment - alignment_coverage - non-symmetrical: coverage of query and subject - similarity_errors - symmetrical: count of similarity errors May throw a ZeroDivisionError if one or more NUCmer runs failed, or a very distant sequence was included in the analysis. """ # Process directory to identify input files - as of v0.2.4 we use the # .filter files that result from delta-filter (1:1 alignments) deltafiles = pyani_files.get_input_files(delta_dir, ".filter") # Hold data in ANIResults object results = ANIResults(list(org_lengths.keys()), "ANIm") # Fill diagonal NA values for alignment_length with org_lengths for org, length in list(org_lengths.items()): results.alignment_lengths[org][org] = length # Process .delta files assuming that the filename format holds: # org1_vs_org2.delta for deltafile in deltafiles: qname, sname = os.path.splitext(os.path.split(deltafile)[-1])[0].split("_vs_") # We may have .delta files from other analyses in the same directory # If this occurs, we raise a warning, and skip the .delta file if qname not in list(org_lengths.keys()): if logger: logger.warning( "Query name %s not in input " % qname + "sequence list, skipping %s" % deltafile ) continue if sname not in list(org_lengths.keys()): if logger: logger.warning( "Subject name %s not in input " % sname + "sequence list, skipping %s" % deltafile ) continue tot_length, tot_sim_error = parse_delta(deltafile) if tot_length == 0 and logger is not None: if logger: logger.warning( "Total alignment length reported in " + "%s is zero!" % deltafile ) query_cover = float(tot_length) / org_lengths[qname] sbjct_cover = float(tot_length) / org_lengths[sname] # Calculate percentage ID of aligned length. This may fail if # total length is zero. # The ZeroDivisionError that would arise should be handled # Common causes are that a NUCmer run failed, or that a very # distant sequence was included in the analysis. try: perc_id = 1 - float(tot_sim_error) / tot_length except ZeroDivisionError: perc_id = 0 # set arbitrary value of zero identity results.zero_error = True # Populate dataframes: when assigning data from symmetrical MUMmer # output, both upper and lower triangles will be populated results.add_tot_length(qname, sname, tot_length) results.add_sim_errors(qname, sname, tot_sim_error) results.add_pid(qname, sname, perc_id) results.add_coverage(qname, sname, query_cover, sbjct_cover) return results
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:write_contigs; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:asm_uid; 5, identifier:contig_uids; 6, default_parameter; 6, 7; 6, 8; 7, identifier:batchsize; 8, integer:10000; 9, block; 9, 10; 9, 12; 9, 13; 9, 21; 9, 22; 9, 48; 9, 60; 9, 87; 9, 88; 9, 112; 9, 113; 9, 125; 9, 126; 9, 147; 9, 148; 9, 149; 9, 150; 9, 158; 9, 346; 9, 359; 9, 360; 9, 371; 10, expression_statement; 10, 11; 11, comment; 12, comment; 13, expression_statement; 13, 14; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:logger; 17, identifier:info; 18, argument_list; 18, 19; 18, 20; 19, string:"Collecting contig data for %s"; 20, identifier:asm_uid; 21, comment; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:asm_record; 25, call; 25, 26; 25, 29; 26, attribute; 26, 27; 26, 28; 27, identifier:Entrez; 28, identifier:read; 29, argument_list; 29, 30; 29, 45; 30, call; 30, 31; 30, 32; 31, identifier:entrez_retry; 32, argument_list; 32, 33; 32, 36; 32, 39; 32, 42; 33, attribute; 33, 34; 33, 35; 34, identifier:Entrez; 35, identifier:esummary; 36, keyword_argument; 36, 37; 36, 38; 37, identifier:db; 38, string:'assembly'; 39, keyword_argument; 39, 40; 39, 41; 40, identifier:id; 41, identifier:asm_uid; 42, keyword_argument; 42, 43; 42, 44; 43, identifier:rettype; 44, string:'text'; 45, keyword_argument; 45, 46; 45, 47; 46, identifier:validate; 47, False; 48, expression_statement; 48, 49; 49, assignment; 49, 50; 49, 51; 50, identifier:asm_organism; 51, subscript; 51, 52; 51, 59; 52, subscript; 52, 53; 52, 58; 53, subscript; 53, 54; 53, 57; 54, subscript; 54, 55; 54, 56; 55, identifier:asm_record; 56, string:'DocumentSummarySet'; 57, string:'DocumentSummary'; 58, integer:0; 59, string:'SpeciesName'; 60, try_statement; 60, 61; 60, 80; 61, block; 61, 62; 62, expression_statement; 62, 63; 63, assignment; 63, 64; 63, 65; 64, identifier:asm_strain; 65, subscript; 65, 66; 65, 79; 66, subscript; 66, 67; 66, 78; 67, subscript; 67, 68; 67, 77; 68, subscript; 68, 69; 68, 76; 69, subscript; 69, 70; 69, 75; 70, subscript; 70, 71; 70, 74; 71, subscript; 71, 72; 71, 73; 72, identifier:asm_record; 73, string:'DocumentSummarySet'; 74, string:'DocumentSummary'; 75, integer:0; 76, string:'Biosource'; 77, string:'InfraspeciesList'; 78, integer:0; 79, string:'Sub_value'; 80, except_clause; 80, 81; 80, 82; 81, identifier:KeyError; 82, block; 82, 83; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:asm_strain; 86, string:""; 87, comment; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:outfilename; 91, binary_operator:%; 91, 92; 91, 93; 92, string:"%s.fasta"; 93, call; 93, 94; 93, 99; 94, attribute; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:os; 97, identifier:path; 98, identifier:join; 99, argument_list; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:args; 102, identifier:outdirname; 103, subscript; 103, 104; 103, 111; 104, subscript; 104, 105; 104, 110; 105, subscript; 105, 106; 105, 109; 106, subscript; 106, 107; 106, 108; 107, identifier:asm_record; 108, string:'DocumentSummarySet'; 109, string:'DocumentSummary'; 110, integer:0; 111, string:'AssemblyAccession'; 112, comment; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 118; 115, pattern_list; 115, 116; 115, 117; 116, identifier:genus; 117, identifier:species; 118, call; 118, 119; 118, 122; 119, attribute; 119, 120; 119, 121; 120, identifier:asm_organism; 121, identifier:split; 122, argument_list; 122, 123; 122, 124; 123, string:' '; 124, integer:1; 125, comment; 126, expression_statement; 126, 127; 127, call; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:logger; 130, identifier:info; 131, argument_list; 131, 132; 131, 133; 131, 134; 132, string:"Downloading FASTA records for assembly %s (%s)"; 133, identifier:asm_uid; 134, call; 134, 135; 134, 138; 135, attribute; 135, 136; 135, 137; 136, string:' '; 137, identifier:join; 138, argument_list; 138, 139; 139, list:[genus[0] + '.', species, asm_strain]; 139, 140; 139, 145; 139, 146; 140, binary_operator:+; 140, 141; 140, 144; 141, subscript; 141, 142; 141, 143; 142, identifier:genus; 143, integer:0; 144, string:'.'; 145, identifier:species; 146, identifier:asm_strain; 147, comment; 148, comment; 149, comment; 150, expression_statement; 150, 151; 151, assignment; 151, 152; 151, 155; 152, pattern_list; 152, 153; 152, 154; 153, identifier:tries; 154, identifier:success; 155, expression_list; 155, 156; 155, 157; 156, integer:0; 157, False; 158, while_statement; 158, 159; 158, 167; 159, boolean_operator:and; 159, 160; 159, 162; 160, not_operator; 160, 161; 161, identifier:success; 162, comparison_operator:<; 162, 163; 162, 164; 163, identifier:tries; 164, attribute; 164, 165; 164, 166; 165, identifier:args; 166, identifier:retries; 167, block; 167, 168; 167, 172; 167, 173; 167, 174; 167, 183; 168, expression_statement; 168, 169; 169, assignment; 169, 170; 169, 171; 170, identifier:records; 171, list:[]; 172, comment; 173, comment; 174, expression_statement; 174, 175; 175, assignment; 175, 176; 175, 177; 176, identifier:query_uids; 177, call; 177, 178; 177, 181; 178, attribute; 178, 179; 178, 180; 179, string:','; 180, identifier:join; 181, argument_list; 181, 182; 182, identifier:contig_uids; 183, try_statement; 183, 184; 183, 319; 184, block; 184, 185; 184, 247; 184, 251; 184, 252; 184, 300; 184, 301; 185, for_statement; 185, 186; 185, 187; 185, 196; 186, identifier:start; 187, call; 187, 188; 187, 189; 188, identifier:range; 189, argument_list; 189, 190; 189, 191; 189, 195; 190, integer:0; 191, call; 191, 192; 191, 193; 192, identifier:len; 193, argument_list; 193, 194; 194, identifier:contig_uids; 195, identifier:batchsize; 196, block; 196, 197; 196, 208; 197, expression_statement; 197, 198; 198, call; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, identifier:logger; 201, identifier:info; 202, argument_list; 202, 203; 202, 204; 202, 205; 203, string:"Batch: %d-%d"; 204, identifier:start; 205, binary_operator:+; 205, 206; 205, 207; 206, identifier:start; 207, identifier:batchsize; 208, expression_statement; 208, 209; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:records; 212, identifier:extend; 213, argument_list; 213, 214; 214, call; 214, 215; 214, 216; 215, identifier:list; 216, argument_list; 216, 217; 217, call; 217, 218; 217, 221; 218, attribute; 218, 219; 218, 220; 219, identifier:SeqIO; 220, identifier:parse; 221, argument_list; 221, 222; 221, 246; 222, call; 222, 223; 222, 224; 223, identifier:entrez_retry; 224, argument_list; 224, 225; 224, 228; 224, 231; 224, 234; 224, 237; 224, 240; 224, 243; 225, attribute; 225, 226; 225, 227; 226, identifier:Entrez; 227, identifier:efetch; 228, keyword_argument; 228, 229; 228, 230; 229, identifier:db; 230, string:'nucleotide'; 231, keyword_argument; 231, 232; 231, 233; 232, identifier:id; 233, identifier:query_uids; 234, keyword_argument; 234, 235; 234, 236; 235, identifier:rettype; 236, string:'fasta'; 237, keyword_argument; 237, 238; 237, 239; 238, identifier:retmode; 239, string:'text'; 240, keyword_argument; 240, 241; 240, 242; 241, identifier:retstart; 242, identifier:start; 243, keyword_argument; 243, 244; 243, 245; 244, identifier:retmax; 245, identifier:batchsize; 246, string:'fasta'; 247, expression_statement; 247, 248; 248, augmented_assignment:+=; 248, 249; 248, 250; 249, identifier:tries; 250, integer:1; 251, comment; 252, if_statement; 252, 253; 252, 262; 252, 267; 253, comparison_operator:==; 253, 254; 253, 258; 254, call; 254, 255; 254, 256; 255, identifier:len; 256, argument_list; 256, 257; 257, identifier:records; 258, call; 258, 259; 258, 260; 259, identifier:len; 260, argument_list; 260, 261; 261, identifier:contig_uids; 262, block; 262, 263; 263, expression_statement; 263, 264; 264, assignment; 264, 265; 264, 266; 265, identifier:success; 266, True; 267, else_clause; 267, 268; 268, block; 268, 269; 268, 284; 268, 292; 269, expression_statement; 269, 270; 270, call; 270, 271; 270, 274; 271, attribute; 271, 272; 271, 273; 272, identifier:logger; 273, identifier:warning; 274, argument_list; 274, 275; 274, 276; 274, 280; 275, string:"%d contigs expected, %d contigs returned"; 276, call; 276, 277; 276, 278; 277, identifier:len; 278, argument_list; 278, 279; 279, identifier:contig_uids; 280, call; 280, 281; 280, 282; 281, identifier:len; 282, argument_list; 282, 283; 283, identifier:records; 284, expression_statement; 284, 285; 285, call; 285, 286; 285, 289; 286, attribute; 286, 287; 286, 288; 287, identifier:logger; 288, identifier:warning; 289, argument_list; 289, 290; 289, 291; 290, string:"FASTA download for assembly %s failed"; 291, identifier:asm_uid; 292, expression_statement; 292, 293; 293, call; 293, 294; 293, 297; 294, attribute; 294, 295; 294, 296; 295, identifier:logger; 296, identifier:warning; 297, argument_list; 297, 298; 297, 299; 298, string:"try %d/20"; 299, identifier:tries; 300, comment; 301, expression_statement; 301, 302; 302, call; 302, 303; 302, 306; 303, attribute; 303, 304; 303, 305; 304, identifier:logger; 305, identifier:info; 306, argument_list; 306, 307; 306, 308; 307, string:"Downloaded genome size: %d"; 308, call; 308, 309; 308, 310; 309, identifier:sum; 310, argument_list; 310, 311; 311, list_comprehension; 311, 312; 311, 316; 312, call; 312, 313; 312, 314; 313, identifier:len; 314, argument_list; 314, 315; 315, identifier:r; 316, for_in_clause; 316, 317; 316, 318; 317, identifier:r; 318, identifier:records; 319, except_clause; 319, 320; 320, block; 320, 321; 320, 329; 320, 338; 321, expression_statement; 321, 322; 322, call; 322, 323; 322, 326; 323, attribute; 323, 324; 323, 325; 324, identifier:logger; 325, identifier:warning; 326, argument_list; 326, 327; 326, 328; 327, string:"FASTA download for assembly %s failed"; 328, identifier:asm_uid; 329, expression_statement; 329, 330; 330, call; 330, 331; 330, 334; 331, attribute; 331, 332; 331, 333; 332, identifier:logger; 333, identifier:warning; 334, argument_list; 334, 335; 335, call; 335, 336; 335, 337; 336, identifier:last_exception; 337, argument_list; 338, expression_statement; 338, 339; 339, call; 339, 340; 339, 343; 340, attribute; 340, 341; 340, 342; 341, identifier:logger; 342, identifier:warning; 343, argument_list; 343, 344; 343, 345; 344, string:"try %d/20"; 345, identifier:tries; 346, if_statement; 346, 347; 346, 349; 346, 350; 347, not_operator; 347, 348; 348, identifier:success; 349, comment; 350, block; 350, 351; 351, expression_statement; 351, 352; 352, call; 352, 353; 352, 356; 353, attribute; 353, 354; 353, 355; 354, identifier:logger; 355, identifier:error; 356, argument_list; 356, 357; 356, 358; 357, string:"Failed to download records for %s (continuing)"; 358, identifier:asm_uid; 359, comment; 360, expression_statement; 360, 361; 361, assignment; 361, 362; 361, 363; 362, identifier:retval; 363, call; 363, 364; 363, 367; 364, attribute; 364, 365; 364, 366; 365, identifier:SeqIO; 366, identifier:write; 367, argument_list; 367, 368; 367, 369; 367, 370; 368, identifier:records; 369, identifier:outfilename; 370, string:'fasta'; 371, expression_statement; 371, 372; 372, call; 372, 373; 372, 376; 373, attribute; 373, 374; 373, 375; 374, identifier:logger; 375, identifier:info; 376, argument_list; 376, 377; 376, 378; 376, 379; 377, string:"Wrote %d contigs to %s"; 378, identifier:retval; 379, identifier:outfilename
def write_contigs(asm_uid, contig_uids, batchsize=10000): """Writes assembly contigs out to a single FASTA file in the script's designated output directory. FASTA records are returned, as GenBank and even GenBankWithParts format records don't reliably give correct sequence in all cases. The script returns two strings for each assembly, a 'class' and a 'label' string - this is for use with, e.g. pyani. """ # Has duplicate code with get_class_label_info() - needs refactoring logger.info("Collecting contig data for %s", asm_uid) # Assembly record - get binomial and strain names asm_record = Entrez.read( entrez_retry( Entrez.esummary, db='assembly', id=asm_uid, rettype='text'), validate=False) asm_organism = asm_record['DocumentSummarySet']['DocumentSummary'][0][ 'SpeciesName'] try: asm_strain = asm_record['DocumentSummarySet']['DocumentSummary'][0][ 'Biosource']['InfraspeciesList'][0]['Sub_value'] except KeyError: asm_strain = "" # Assembly UID (long form) for the output filename outfilename = "%s.fasta" % os.path.join(args.outdirname, asm_record[ 'DocumentSummarySet']['DocumentSummary'][0]['AssemblyAccession']) # Create label and class strings genus, species = asm_organism.split(' ', 1) # Get FASTA records for contigs logger.info("Downloading FASTA records for assembly %s (%s)", asm_uid, ' '.join([genus[0] + '.', species, asm_strain])) # We're doing an explicit outer retry loop here because we want to confirm # we have the correct data, as well as test for Entrez connection errors, # which is all the entrez_retry function does. tries, success = 0, False while not success and tries < args.retries: records = [] # Holds all return records # We may need to batch contigs query_uids = ','.join(contig_uids) try: for start in range(0, len(contig_uids), batchsize): logger.info("Batch: %d-%d", start, start + batchsize) records.extend( list( SeqIO.parse( entrez_retry( Entrez.efetch, db='nucleotide', id=query_uids, rettype='fasta', retmode='text', retstart=start, retmax=batchsize), 'fasta'))) tries += 1 # Check only that correct number of records returned. if len(records) == len(contig_uids): success = True else: logger.warning("%d contigs expected, %d contigs returned", len(contig_uids), len(records)) logger.warning("FASTA download for assembly %s failed", asm_uid) logger.warning("try %d/20", tries) # Could also check expected assembly sequence length? logger.info("Downloaded genome size: %d", sum([len(r) for r in records])) except: logger.warning("FASTA download for assembly %s failed", asm_uid) logger.warning(last_exception()) logger.warning("try %d/20", tries) if not success: # Could place option on command-line to stop or continue here. logger.error("Failed to download records for %s (continuing)", asm_uid) # Write contigs to file retval = SeqIO.write(records, outfilename, 'fasta') logger.info("Wrote %d contigs to %s", retval, outfilename)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:calculate_tetra_zscore; 3, parameters; 3, 4; 4, identifier:filename; 5, block; 5, 6; 5, 8; 5, 9; 5, 10; 5, 11; 5, 39; 5, 268; 5, 269; 5, 270; 5, 274; 5, 327; 5, 328; 5, 329; 5, 333; 5, 337; 5, 458; 6, expression_statement; 6, 7; 7, comment; 8, comment; 9, comment; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:counts; 14, tuple; 14, 15; 14, 21; 14, 27; 14, 33; 15, call; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, identifier:collections; 18, identifier:defaultdict; 19, argument_list; 19, 20; 20, identifier:int; 21, call; 21, 22; 21, 25; 22, attribute; 22, 23; 22, 24; 23, identifier:collections; 24, identifier:defaultdict; 25, argument_list; 25, 26; 26, identifier:int; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:collections; 30, identifier:defaultdict; 31, argument_list; 31, 32; 32, identifier:int; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:collections; 36, identifier:defaultdict; 37, argument_list; 37, 38; 38, identifier:int; 39, for_statement; 39, 40; 39, 41; 39, 48; 40, identifier:rec; 41, call; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:SeqIO; 44, identifier:parse; 45, argument_list; 45, 46; 45, 47; 46, identifier:filename; 47, string:'fasta'; 48, block; 48, 49; 49, for_statement; 49, 50; 49, 51; 49, 76; 49, 77; 49, 78; 50, identifier:seq; 51, list:[str(rec.seq).upper(), str(rec.seq.reverse_complement()).upper()]; 51, 52; 51, 62; 52, call; 52, 53; 52, 61; 53, attribute; 53, 54; 53, 60; 54, call; 54, 55; 54, 56; 55, identifier:str; 56, argument_list; 56, 57; 57, attribute; 57, 58; 57, 59; 58, identifier:rec; 59, identifier:seq; 60, identifier:upper; 61, argument_list; 62, call; 62, 63; 62, 75; 63, attribute; 63, 64; 63, 74; 64, call; 64, 65; 64, 66; 65, identifier:str; 66, argument_list; 66, 67; 67, call; 67, 68; 67, 73; 68, attribute; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:rec; 71, identifier:seq; 72, identifier:reverse_complement; 73, argument_list; 74, identifier:upper; 75, argument_list; 76, comment; 77, comment; 78, block; 78, 79; 78, 100; 78, 101; 78, 102; 78, 181; 78, 182; 78, 200; 78, 216; 78, 234; 78, 252; 79, for_statement; 79, 80; 79, 81; 79, 86; 80, identifier:base; 81, tuple; 81, 82; 81, 83; 81, 84; 81, 85; 82, string:'G'; 83, string:'C'; 84, string:'T'; 85, string:'A'; 86, block; 86, 87; 87, expression_statement; 87, 88; 88, augmented_assignment:+=; 88, 89; 88, 94; 89, subscript; 89, 90; 89, 93; 90, subscript; 90, 91; 90, 92; 91, identifier:counts; 92, integer:0; 93, identifier:base; 94, call; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:seq; 97, identifier:count; 98, argument_list; 98, 99; 99, identifier:base; 100, comment; 101, comment; 102, for_statement; 102, 103; 102, 104; 102, 116; 103, identifier:i; 104, call; 104, 105; 104, 106; 105, identifier:range; 106, argument_list; 106, 107; 107, call; 107, 108; 107, 109; 108, identifier:len; 109, argument_list; 109, 110; 110, subscript; 110, 111; 110, 112; 111, identifier:seq; 112, slice; 112, 113; 112, 114; 113, colon; 114, unary_operator:-; 114, 115; 115, integer:4; 116, block; 116, 117; 116, 148; 116, 159; 116, 170; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 123; 119, pattern_list; 119, 120; 119, 121; 119, 122; 120, identifier:din; 121, identifier:tri; 122, identifier:tetra; 123, expression_list; 123, 124; 123, 132; 123, 140; 124, subscript; 124, 125; 124, 126; 125, identifier:seq; 126, slice; 126, 127; 126, 128; 126, 129; 127, identifier:i; 128, colon; 129, binary_operator:+; 129, 130; 129, 131; 130, identifier:i; 131, integer:2; 132, subscript; 132, 133; 132, 134; 133, identifier:seq; 134, slice; 134, 135; 134, 136; 134, 137; 135, identifier:i; 136, colon; 137, binary_operator:+; 137, 138; 137, 139; 138, identifier:i; 139, integer:3; 140, subscript; 140, 141; 140, 142; 141, identifier:seq; 142, slice; 142, 143; 142, 144; 142, 145; 143, identifier:i; 144, colon; 145, binary_operator:+; 145, 146; 145, 147; 146, identifier:i; 147, integer:4; 148, expression_statement; 148, 149; 149, augmented_assignment:+=; 149, 150; 149, 158; 150, subscript; 150, 151; 150, 154; 151, subscript; 151, 152; 151, 153; 152, identifier:counts; 153, integer:1; 154, call; 154, 155; 154, 156; 155, identifier:str; 156, argument_list; 156, 157; 157, identifier:din; 158, integer:1; 159, expression_statement; 159, 160; 160, augmented_assignment:+=; 160, 161; 160, 169; 161, subscript; 161, 162; 161, 165; 162, subscript; 162, 163; 162, 164; 163, identifier:counts; 164, integer:2; 165, call; 165, 166; 165, 167; 166, identifier:str; 167, argument_list; 167, 168; 168, identifier:tri; 169, integer:1; 170, expression_statement; 170, 171; 171, augmented_assignment:+=; 171, 172; 171, 180; 172, subscript; 172, 173; 172, 176; 173, subscript; 173, 174; 173, 175; 174, identifier:counts; 175, integer:3; 176, call; 176, 177; 176, 178; 177, identifier:str; 178, argument_list; 178, 179; 179, identifier:tetra; 180, integer:1; 181, comment; 182, expression_statement; 182, 183; 183, augmented_assignment:+=; 183, 184; 183, 199; 184, subscript; 184, 185; 184, 188; 185, subscript; 185, 186; 185, 187; 186, identifier:counts; 187, integer:2; 188, call; 188, 189; 188, 190; 189, identifier:str; 190, argument_list; 190, 191; 191, subscript; 191, 192; 191, 193; 192, identifier:seq; 193, slice; 193, 194; 193, 196; 193, 197; 194, unary_operator:-; 194, 195; 195, integer:4; 196, colon; 197, unary_operator:-; 197, 198; 198, integer:1; 199, integer:1; 200, expression_statement; 200, 201; 201, augmented_assignment:+=; 201, 202; 201, 215; 202, subscript; 202, 203; 202, 206; 203, subscript; 203, 204; 203, 205; 204, identifier:counts; 205, integer:2; 206, call; 206, 207; 206, 208; 207, identifier:str; 208, argument_list; 208, 209; 209, subscript; 209, 210; 209, 211; 210, identifier:seq; 211, slice; 211, 212; 211, 214; 212, unary_operator:-; 212, 213; 213, integer:3; 214, colon; 215, integer:1; 216, expression_statement; 216, 217; 217, augmented_assignment:+=; 217, 218; 217, 233; 218, subscript; 218, 219; 218, 222; 219, subscript; 219, 220; 219, 221; 220, identifier:counts; 221, integer:1; 222, call; 222, 223; 222, 224; 223, identifier:str; 224, argument_list; 224, 225; 225, subscript; 225, 226; 225, 227; 226, identifier:seq; 227, slice; 227, 228; 227, 230; 227, 231; 228, unary_operator:-; 228, 229; 229, integer:4; 230, colon; 231, unary_operator:-; 231, 232; 232, integer:2; 233, integer:1; 234, expression_statement; 234, 235; 235, augmented_assignment:+=; 235, 236; 235, 251; 236, subscript; 236, 237; 236, 240; 237, subscript; 237, 238; 237, 239; 238, identifier:counts; 239, integer:1; 240, call; 240, 241; 240, 242; 241, identifier:str; 242, argument_list; 242, 243; 243, subscript; 243, 244; 243, 245; 244, identifier:seq; 245, slice; 245, 246; 245, 248; 245, 249; 246, unary_operator:-; 246, 247; 247, integer:3; 248, colon; 249, unary_operator:-; 249, 250; 250, integer:1; 251, integer:1; 252, expression_statement; 252, 253; 253, augmented_assignment:+=; 253, 254; 253, 267; 254, subscript; 254, 255; 254, 258; 255, subscript; 255, 256; 255, 257; 256, identifier:counts; 257, integer:1; 258, call; 258, 259; 258, 260; 259, identifier:str; 260, argument_list; 260, 261; 261, subscript; 261, 262; 261, 263; 262, identifier:seq; 263, slice; 263, 264; 263, 266; 264, unary_operator:-; 264, 265; 265, integer:2; 266, colon; 267, integer:1; 268, comment; 269, comment; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:tetra_exp; 273, dictionary; 274, for_statement; 274, 275; 274, 276; 274, 288; 275, identifier:tet; 276, list_comprehension; 276, 277; 276, 278; 276, 283; 277, identifier:tetn; 278, for_in_clause; 278, 279; 278, 280; 279, identifier:tetn; 280, subscript; 280, 281; 280, 282; 281, identifier:counts; 282, integer:3; 283, if_clause; 283, 284; 284, call; 284, 285; 284, 286; 285, identifier:tetra_clean; 286, argument_list; 286, 287; 287, identifier:tetn; 288, block; 288, 289; 289, expression_statement; 289, 290; 290, assignment; 290, 291; 290, 294; 291, subscript; 291, 292; 291, 293; 292, identifier:tetra_exp; 293, identifier:tet; 294, binary_operator:/; 294, 295; 294, 316; 294, 317; 295, binary_operator:*; 295, 296; 295, 307; 296, binary_operator:*; 296, 297; 296, 298; 297, float:1.; 298, subscript; 298, 299; 298, 302; 299, subscript; 299, 300; 299, 301; 300, identifier:counts; 301, integer:2; 302, subscript; 302, 303; 302, 304; 303, identifier:tet; 304, slice; 304, 305; 304, 306; 305, colon; 306, integer:3; 307, subscript; 307, 308; 307, 311; 308, subscript; 308, 309; 308, 310; 309, identifier:counts; 310, integer:2; 311, subscript; 311, 312; 311, 313; 312, identifier:tet; 313, slice; 313, 314; 313, 315; 314, integer:1; 315, colon; 316, line_continuation:\; 317, subscript; 317, 318; 317, 321; 318, subscript; 318, 319; 318, 320; 319, identifier:counts; 320, integer:1; 321, subscript; 321, 322; 321, 323; 322, identifier:tet; 323, slice; 323, 324; 323, 325; 323, 326; 324, integer:1; 325, colon; 326, integer:3; 327, comment; 328, comment; 329, expression_statement; 329, 330; 330, assignment; 330, 331; 330, 332; 331, identifier:tetra_sd; 332, dictionary; 333, expression_statement; 333, 334; 334, assignment; 334, 335; 334, 336; 335, identifier:tetra_z; 336, dictionary; 337, for_statement; 337, 338; 337, 341; 337, 349; 338, pattern_list; 338, 339; 338, 340; 339, identifier:tet; 340, identifier:exp; 341, call; 341, 342; 341, 343; 342, identifier:list; 343, argument_list; 343, 344; 344, call; 344, 345; 344, 348; 345, attribute; 345, 346; 345, 347; 346, identifier:tetra_exp; 347, identifier:items; 348, argument_list; 349, block; 349, 350; 349, 363; 349, 405; 350, expression_statement; 350, 351; 351, assignment; 351, 352; 351, 353; 352, identifier:den; 353, subscript; 353, 354; 353, 357; 354, subscript; 354, 355; 354, 356; 355, identifier:counts; 356, integer:1; 357, subscript; 357, 358; 357, 359; 358, identifier:tet; 359, slice; 359, 360; 359, 361; 359, 362; 360, integer:1; 361, colon; 362, integer:3; 363, expression_statement; 363, 364; 364, assignment; 364, 365; 364, 368; 365, subscript; 365, 366; 365, 367; 366, identifier:tetra_sd; 367, identifier:tet; 368, call; 368, 369; 368, 372; 369, attribute; 369, 370; 369, 371; 370, identifier:math; 371, identifier:sqrt; 372, argument_list; 372, 373; 373, binary_operator:/; 373, 374; 373, 401; 374, binary_operator:*; 374, 375; 374, 389; 375, binary_operator:*; 375, 376; 375, 377; 376, identifier:exp; 377, parenthesized_expression; 377, 378; 378, binary_operator:-; 378, 379; 378, 380; 379, identifier:den; 380, subscript; 380, 381; 380, 384; 381, subscript; 381, 382; 381, 383; 382, identifier:counts; 383, integer:2; 384, subscript; 384, 385; 384, 386; 385, identifier:tet; 386, slice; 386, 387; 386, 388; 387, colon; 388, integer:3; 389, parenthesized_expression; 389, 390; 390, binary_operator:-; 390, 391; 390, 392; 391, identifier:den; 392, subscript; 392, 393; 392, 396; 393, subscript; 393, 394; 393, 395; 394, identifier:counts; 395, integer:2; 396, subscript; 396, 397; 396, 398; 397, identifier:tet; 398, slice; 398, 399; 398, 400; 399, integer:1; 400, colon; 401, parenthesized_expression; 401, 402; 402, binary_operator:*; 402, 403; 402, 404; 403, identifier:den; 404, identifier:den; 405, try_statement; 405, 406; 405, 424; 406, block; 406, 407; 407, expression_statement; 407, 408; 408, assignment; 408, 409; 408, 412; 409, subscript; 409, 410; 409, 411; 410, identifier:tetra_z; 411, identifier:tet; 412, binary_operator:/; 412, 413; 412, 421; 413, parenthesized_expression; 413, 414; 414, binary_operator:-; 414, 415; 414, 420; 415, subscript; 415, 416; 415, 419; 416, subscript; 416, 417; 416, 418; 417, identifier:counts; 418, integer:3; 419, identifier:tet; 420, identifier:exp; 421, subscript; 421, 422; 421, 423; 422, identifier:tetra_sd; 423, identifier:tet; 424, except_clause; 424, 425; 424, 426; 424, 427; 424, 428; 425, identifier:ZeroDivisionError; 426, comment; 427, comment; 428, block; 428, 429; 429, expression_statement; 429, 430; 430, assignment; 430, 431; 430, 434; 431, subscript; 431, 432; 431, 433; 432, identifier:tetra_z; 433, identifier:tet; 434, binary_operator:/; 434, 435; 434, 436; 435, integer:1; 436, parenthesized_expression; 436, 437; 437, binary_operator:*; 437, 438; 437, 448; 438, subscript; 438, 439; 438, 442; 439, subscript; 439, 440; 439, 441; 440, identifier:counts; 441, integer:1; 442, subscript; 442, 443; 442, 444; 443, identifier:tet; 444, slice; 444, 445; 444, 446; 444, 447; 445, integer:1; 446, colon; 447, integer:3; 448, subscript; 448, 449; 448, 452; 449, subscript; 449, 450; 449, 451; 450, identifier:counts; 451, integer:1; 452, subscript; 452, 453; 452, 454; 453, identifier:tet; 454, slice; 454, 455; 454, 456; 454, 457; 455, integer:1; 456, colon; 457, integer:3; 458, return_statement; 458, 459; 459, identifier:tetra_z
def calculate_tetra_zscore(filename): """Returns TETRA Z-score for the sequence in the passed file. - filename - path to sequence file Calculates mono-, di-, tri- and tetranucleotide frequencies for each sequence, on each strand, and follows Teeling et al. (2004) in calculating a corresponding Z-score for each observed tetranucleotide frequency, dependent on the mono-, di- and tri- nucleotide frequencies for that input sequence. """ # For the Teeling et al. method, the Z-scores require us to count # mono, di, tri and tetranucleotide sequences - these are stored # (in order) in the counts tuple counts = (collections.defaultdict(int), collections.defaultdict(int), collections.defaultdict(int), collections.defaultdict(int)) for rec in SeqIO.parse(filename, 'fasta'): for seq in [str(rec.seq).upper(), str(rec.seq.reverse_complement()).upper()]: # The Teeling et al. algorithm requires us to consider # both strand orientations, so monocounts are easy for base in ('G', 'C', 'T', 'A'): counts[0][base] += seq.count(base) # For di, tri and tetranucleotide counts, loop over the # sequence and its reverse complement, until near the end: for i in range(len(seq[:-4])): din, tri, tetra = seq[i:i+2], seq[i:i+3], seq[i:i+4] counts[1][str(din)] += 1 counts[2][str(tri)] += 1 counts[3][str(tetra)] += 1 # Then clean up the straggling bit at the end: counts[2][str(seq[-4:-1])] += 1 counts[2][str(seq[-3:])] += 1 counts[1][str(seq[-4:-2])] += 1 counts[1][str(seq[-3:-1])] += 1 counts[1][str(seq[-2:])] += 1 # Following Teeling (2004), calculate expected frequencies for each # tetranucleotide; we ignore ambiguity symbols tetra_exp = {} for tet in [tetn for tetn in counts[3] if tetra_clean(tetn)]: tetra_exp[tet] = 1. * counts[2][tet[:3]] * counts[2][tet[1:]] / \ counts[1][tet[1:3]] # Following Teeling (2004) we approximate the std dev and Z-score for each # tetranucleotide tetra_sd = {} tetra_z = {} for tet, exp in list(tetra_exp.items()): den = counts[1][tet[1:3]] tetra_sd[tet] = math.sqrt(exp * (den - counts[2][tet[:3]]) * (den - counts[2][tet[1:]]) / (den * den)) try: tetra_z[tet] = (counts[3][tet] - exp)/tetra_sd[tet] except ZeroDivisionError: # To record if we hit a zero in the estimation of variance # zeroes = [k for k, v in list(tetra_sd.items()) if v == 0] tetra_z[tet] = 1 / (counts[1][tet[1:3]] * counts[1][tet[1:3]]) return tetra_z
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:calculate_correlations; 3, parameters; 3, 4; 4, identifier:tetra_z; 5, block; 5, 6; 5, 8; 5, 19; 5, 41; 5, 255; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:orgs; 11, call; 11, 12; 11, 13; 12, identifier:sorted; 13, argument_list; 13, 14; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:tetra_z; 17, identifier:keys; 18, argument_list; 19, expression_statement; 19, 20; 20, assignment; 20, 21; 20, 22; 21, identifier:correlations; 22, call; 22, 23; 22, 39; 23, attribute; 23, 24; 23, 38; 24, call; 24, 25; 24, 28; 25, attribute; 25, 26; 25, 27; 26, identifier:pd; 27, identifier:DataFrame; 28, argument_list; 28, 29; 28, 32; 28, 35; 29, keyword_argument; 29, 30; 29, 31; 30, identifier:index; 31, identifier:orgs; 32, keyword_argument; 32, 33; 32, 34; 33, identifier:columns; 34, identifier:orgs; 35, keyword_argument; 35, 36; 35, 37; 36, identifier:dtype; 37, identifier:float; 38, identifier:fillna; 39, argument_list; 39, 40; 40, float:1.0; 41, for_statement; 41, 42; 41, 45; 41, 54; 42, pattern_list; 42, 43; 42, 44; 43, identifier:idx; 44, identifier:org1; 45, call; 45, 46; 45, 47; 46, identifier:enumerate; 47, argument_list; 47, 48; 48, subscript; 48, 49; 48, 50; 49, identifier:orgs; 50, slice; 50, 51; 50, 52; 51, colon; 52, unary_operator:-; 52, 53; 53, integer:1; 54, block; 54, 55; 55, for_statement; 55, 56; 55, 57; 55, 64; 56, identifier:org2; 57, subscript; 57, 58; 57, 59; 58, identifier:orgs; 59, slice; 59, 60; 59, 63; 60, binary_operator:+; 60, 61; 60, 62; 61, identifier:idx; 62, integer:1; 63, colon; 64, block; 64, 65; 64, 87; 64, 100; 64, 122; 64, 138; 64, 164; 64, 193; 64, 221; 64, 243; 65, assert_statement; 65, 66; 66, comparison_operator:==; 66, 67; 66, 77; 67, call; 67, 68; 67, 69; 68, identifier:sorted; 69, argument_list; 69, 70; 70, call; 70, 71; 70, 76; 71, attribute; 71, 72; 71, 75; 72, subscript; 72, 73; 72, 74; 73, identifier:tetra_z; 74, identifier:org1; 75, identifier:keys; 76, argument_list; 77, call; 77, 78; 77, 79; 78, identifier:sorted; 79, argument_list; 79, 80; 80, call; 80, 81; 80, 86; 81, attribute; 81, 82; 81, 85; 82, subscript; 82, 83; 82, 84; 83, identifier:tetra_z; 84, identifier:org2; 85, identifier:keys; 86, argument_list; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:tets; 90, call; 90, 91; 90, 92; 91, identifier:sorted; 92, argument_list; 92, 93; 93, call; 93, 94; 93, 99; 94, attribute; 94, 95; 94, 98; 95, subscript; 95, 96; 95, 97; 96, identifier:tetra_z; 97, identifier:org1; 98, identifier:keys; 99, argument_list; 100, expression_statement; 100, 101; 101, assignment; 101, 102; 101, 103; 102, identifier:zscores; 103, list:[[tetra_z[org1][t] for t in tets], [tetra_z[org2][t] for t in tets]]; 103, 104; 103, 113; 104, list_comprehension; 104, 105; 104, 110; 105, subscript; 105, 106; 105, 109; 106, subscript; 106, 107; 106, 108; 107, identifier:tetra_z; 108, identifier:org1; 109, identifier:t; 110, for_in_clause; 110, 111; 110, 112; 111, identifier:t; 112, identifier:tets; 113, list_comprehension; 113, 114; 113, 119; 114, subscript; 114, 115; 114, 118; 115, subscript; 115, 116; 115, 117; 116, identifier:tetra_z; 117, identifier:org2; 118, identifier:t; 119, for_in_clause; 119, 120; 119, 121; 120, identifier:t; 121, identifier:tets; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:zmeans; 125, list_comprehension; 125, 126; 125, 135; 126, binary_operator:/; 126, 127; 126, 131; 127, call; 127, 128; 127, 129; 128, identifier:sum; 129, argument_list; 129, 130; 130, identifier:zscore; 131, call; 131, 132; 131, 133; 132, identifier:len; 133, argument_list; 133, 134; 134, identifier:zscore; 135, for_in_clause; 135, 136; 135, 137; 136, identifier:zscore; 137, identifier:zscores; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:zdiffs; 141, list:[[z - zmeans[0] for z in zscores[0]], [z - zmeans[1] for z in zscores[1]]]; 141, 142; 141, 153; 142, list_comprehension; 142, 143; 142, 148; 143, binary_operator:-; 143, 144; 143, 145; 144, identifier:z; 145, subscript; 145, 146; 145, 147; 146, identifier:zmeans; 147, integer:0; 148, for_in_clause; 148, 149; 148, 150; 149, identifier:z; 150, subscript; 150, 151; 150, 152; 151, identifier:zscores; 152, integer:0; 153, list_comprehension; 153, 154; 153, 159; 154, binary_operator:-; 154, 155; 154, 156; 155, identifier:z; 156, subscript; 156, 157; 156, 158; 157, identifier:zmeans; 158, integer:1; 159, for_in_clause; 159, 160; 159, 161; 160, identifier:z; 161, subscript; 161, 162; 161, 163; 162, identifier:zscores; 163, integer:1; 164, expression_statement; 164, 165; 165, assignment; 165, 166; 165, 167; 166, identifier:diffprods; 167, call; 167, 168; 167, 169; 168, identifier:sum; 169, argument_list; 169, 170; 170, list_comprehension; 170, 171; 170, 182; 171, binary_operator:*; 171, 172; 171, 177; 172, subscript; 172, 173; 172, 176; 173, subscript; 173, 174; 173, 175; 174, identifier:zdiffs; 175, integer:0; 176, identifier:i; 177, subscript; 177, 178; 177, 181; 178, subscript; 178, 179; 178, 180; 179, identifier:zdiffs; 180, integer:1; 181, identifier:i; 182, for_in_clause; 182, 183; 182, 184; 183, identifier:i; 184, call; 184, 185; 184, 186; 185, identifier:range; 186, argument_list; 186, 187; 187, call; 187, 188; 187, 189; 188, identifier:len; 189, argument_list; 189, 190; 190, subscript; 190, 191; 190, 192; 191, identifier:zdiffs; 192, integer:0; 193, expression_statement; 193, 194; 194, assignment; 194, 195; 194, 196; 195, identifier:zdiffs2; 196, list:[sum([z * z for z in zdiffs[0]]), sum([z * z for z in zdiffs[1]])]; 196, 197; 196, 209; 197, call; 197, 198; 197, 199; 198, identifier:sum; 199, argument_list; 199, 200; 200, list_comprehension; 200, 201; 200, 204; 201, binary_operator:*; 201, 202; 201, 203; 202, identifier:z; 203, identifier:z; 204, for_in_clause; 204, 205; 204, 206; 205, identifier:z; 206, subscript; 206, 207; 206, 208; 207, identifier:zdiffs; 208, integer:0; 209, call; 209, 210; 209, 211; 210, identifier:sum; 211, argument_list; 211, 212; 212, list_comprehension; 212, 213; 212, 216; 213, binary_operator:*; 213, 214; 213, 215; 214, identifier:z; 215, identifier:z; 216, for_in_clause; 216, 217; 216, 218; 217, identifier:z; 218, subscript; 218, 219; 218, 220; 219, identifier:zdiffs; 220, integer:1; 221, expression_statement; 221, 222; 222, assignment; 222, 223; 222, 228; 223, subscript; 223, 224; 223, 227; 224, subscript; 224, 225; 224, 226; 225, identifier:correlations; 226, identifier:org1; 227, identifier:org2; 228, binary_operator:/; 228, 229; 228, 230; 228, 231; 229, identifier:diffprods; 230, line_continuation:\; 231, call; 231, 232; 231, 235; 232, attribute; 232, 233; 232, 234; 233, identifier:math; 234, identifier:sqrt; 235, argument_list; 235, 236; 236, binary_operator:*; 236, 237; 236, 240; 237, subscript; 237, 238; 237, 239; 238, identifier:zdiffs2; 239, integer:0; 240, subscript; 240, 241; 240, 242; 241, identifier:zdiffs2; 242, integer:1; 243, expression_statement; 243, 244; 244, assignment; 244, 245; 244, 250; 245, subscript; 245, 246; 245, 249; 246, subscript; 246, 247; 246, 248; 247, identifier:correlations; 248, identifier:org2; 249, identifier:org1; 250, subscript; 250, 251; 250, 254; 251, subscript; 251, 252; 251, 253; 252, identifier:correlations; 253, identifier:org1; 254, identifier:org2; 255, return_statement; 255, 256; 256, identifier:correlations
def calculate_correlations(tetra_z): """Returns dataframe of Pearson correlation coefficients. - tetra_z - dictionary of Z-scores, keyed by sequence ID Calculates Pearson correlation coefficient from Z scores for each tetranucleotide. This is done longhand here, which is fast enough, but for robustness we might want to do something else... (TODO). Note that we report a correlation by this method, rather than a percentage identity. """ orgs = sorted(tetra_z.keys()) correlations = pd.DataFrame(index=orgs, columns=orgs, dtype=float).fillna(1.0) for idx, org1 in enumerate(orgs[:-1]): for org2 in orgs[idx+1:]: assert sorted(tetra_z[org1].keys()) == sorted(tetra_z[org2].keys()) tets = sorted(tetra_z[org1].keys()) zscores = [[tetra_z[org1][t] for t in tets], [tetra_z[org2][t] for t in tets]] zmeans = [sum(zscore)/len(zscore) for zscore in zscores] zdiffs = [[z - zmeans[0] for z in zscores[0]], [z - zmeans[1] for z in zscores[1]]] diffprods = sum([zdiffs[0][i] * zdiffs[1][i] for i in range(len(zdiffs[0]))]) zdiffs2 = [sum([z * z for z in zdiffs[0]]), sum([z * z for z in zdiffs[1]])] correlations[org1][org2] = diffprods / \ math.sqrt(zdiffs2[0] * zdiffs2[1]) correlations[org2][org1] = correlations[org1][org2] return correlations
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 21; 2, function_name:process_blast; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 4, identifier:blast_dir; 5, identifier:org_lengths; 6, default_parameter; 6, 7; 6, 8; 7, identifier:fraglengths; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:mode; 11, string:"ANIb"; 12, default_parameter; 12, 13; 12, 14; 13, identifier:identity; 14, float:0.3; 15, default_parameter; 15, 16; 15, 17; 16, identifier:coverage; 17, float:0.7; 18, default_parameter; 18, 19; 18, 20; 19, identifier:logger; 20, None; 21, block; 21, 22; 21, 24; 21, 25; 21, 35; 21, 36; 21, 51; 21, 52; 21, 75; 21, 76; 21, 77; 21, 251; 22, expression_statement; 22, 23; 23, comment; 24, comment; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:blastfiles; 28, call; 28, 29; 28, 32; 29, attribute; 29, 30; 29, 31; 30, identifier:pyani_files; 31, identifier:get_input_files; 32, argument_list; 32, 33; 32, 34; 33, identifier:blast_dir; 34, string:".blast_tab"; 35, comment; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:results; 39, call; 39, 40; 39, 41; 40, identifier:ANIResults; 41, argument_list; 41, 42; 41, 50; 42, call; 42, 43; 42, 44; 43, identifier:list; 44, argument_list; 44, 45; 45, call; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:org_lengths; 48, identifier:keys; 49, argument_list; 50, identifier:mode; 51, comment; 52, for_statement; 52, 53; 52, 56; 52, 64; 53, pattern_list; 53, 54; 53, 55; 54, identifier:org; 55, identifier:length; 56, call; 56, 57; 56, 58; 57, identifier:list; 58, argument_list; 58, 59; 59, call; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:org_lengths; 62, identifier:items; 63, argument_list; 64, block; 64, 65; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 74; 67, subscript; 67, 68; 67, 73; 68, subscript; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:results; 71, identifier:alignment_lengths; 72, identifier:org; 73, identifier:org; 74, identifier:length; 75, comment; 76, comment; 77, for_statement; 77, 78; 77, 79; 77, 80; 78, identifier:blastfile; 79, identifier:blastfiles; 80, block; 80, 81; 80, 111; 80, 112; 80, 113; 80, 142; 80, 171; 80, 182; 80, 195; 80, 196; 80, 197; 80, 198; 80, 212; 80, 226; 80, 242; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 86; 83, pattern_list; 83, 84; 83, 85; 84, identifier:qname; 85, identifier:sname; 86, call; 86, 87; 86, 109; 87, attribute; 87, 88; 87, 108; 88, subscript; 88, 89; 88, 107; 89, call; 89, 90; 89, 95; 90, attribute; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:os; 93, identifier:path; 94, identifier:splitext; 95, argument_list; 95, 96; 96, subscript; 96, 97; 96, 105; 97, call; 97, 98; 97, 103; 98, attribute; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, identifier:os; 101, identifier:path; 102, identifier:split; 103, argument_list; 103, 104; 104, identifier:blastfile; 105, unary_operator:-; 105, 106; 106, integer:1; 107, integer:0; 108, identifier:split; 109, argument_list; 109, 110; 110, string:"_vs_"; 111, comment; 112, comment; 113, if_statement; 113, 114; 113, 124; 114, comparison_operator:not; 114, 115; 114, 116; 115, identifier:qname; 116, call; 116, 117; 116, 118; 117, identifier:list; 118, argument_list; 118, 119; 119, call; 119, 120; 119, 123; 120, attribute; 120, 121; 120, 122; 121, identifier:org_lengths; 122, identifier:keys; 123, argument_list; 124, block; 124, 125; 124, 141; 125, if_statement; 125, 126; 125, 127; 126, identifier:logger; 127, block; 127, 128; 128, expression_statement; 128, 129; 129, call; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:logger; 132, identifier:warning; 133, argument_list; 133, 134; 134, binary_operator:+; 134, 135; 134, 138; 135, binary_operator:%; 135, 136; 135, 137; 136, string:"Query name %s not in input "; 137, identifier:qname; 138, binary_operator:%; 138, 139; 138, 140; 139, string:"sequence list, skipping %s"; 140, identifier:blastfile; 141, continue_statement; 142, if_statement; 142, 143; 142, 153; 143, comparison_operator:not; 143, 144; 143, 145; 144, identifier:sname; 145, call; 145, 146; 145, 147; 146, identifier:list; 147, argument_list; 147, 148; 148, call; 148, 149; 148, 152; 149, attribute; 149, 150; 149, 151; 150, identifier:org_lengths; 151, identifier:keys; 152, argument_list; 153, block; 153, 154; 153, 170; 154, if_statement; 154, 155; 154, 156; 155, identifier:logger; 156, block; 156, 157; 157, expression_statement; 157, 158; 158, call; 158, 159; 158, 162; 159, attribute; 159, 160; 159, 161; 160, identifier:logger; 161, identifier:warning; 162, argument_list; 162, 163; 163, binary_operator:+; 163, 164; 163, 167; 164, binary_operator:%; 164, 165; 164, 166; 165, string:"Subject name %s not in input "; 166, identifier:sname; 167, binary_operator:%; 167, 168; 167, 169; 168, string:"sequence list, skipping %s"; 169, identifier:blastfile; 170, continue_statement; 171, expression_statement; 171, 172; 172, assignment; 172, 173; 172, 174; 173, identifier:resultvals; 174, call; 174, 175; 174, 176; 175, identifier:parse_blast_tab; 176, argument_list; 176, 177; 176, 178; 176, 179; 176, 180; 176, 181; 177, identifier:blastfile; 178, identifier:fraglengths; 179, identifier:identity; 180, identifier:coverage; 181, identifier:mode; 182, expression_statement; 182, 183; 183, assignment; 183, 184; 183, 185; 184, identifier:query_cover; 185, binary_operator:/; 185, 186; 185, 192; 186, call; 186, 187; 186, 188; 187, identifier:float; 188, argument_list; 188, 189; 189, subscript; 189, 190; 189, 191; 190, identifier:resultvals; 191, integer:0; 192, subscript; 192, 193; 192, 194; 193, identifier:org_lengths; 194, identifier:qname; 195, comment; 196, comment; 197, comment; 198, expression_statement; 198, 199; 199, call; 199, 200; 199, 203; 200, attribute; 200, 201; 200, 202; 201, identifier:results; 202, identifier:add_tot_length; 203, argument_list; 203, 204; 203, 205; 203, 206; 203, 209; 204, identifier:qname; 205, identifier:sname; 206, subscript; 206, 207; 206, 208; 207, identifier:resultvals; 208, integer:0; 209, keyword_argument; 209, 210; 209, 211; 210, identifier:sym; 211, False; 212, expression_statement; 212, 213; 213, call; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:results; 216, identifier:add_sim_errors; 217, argument_list; 217, 218; 217, 219; 217, 220; 217, 223; 218, identifier:qname; 219, identifier:sname; 220, subscript; 220, 221; 220, 222; 221, identifier:resultvals; 222, integer:1; 223, keyword_argument; 223, 224; 223, 225; 224, identifier:sym; 225, False; 226, expression_statement; 226, 227; 227, call; 227, 228; 227, 231; 228, attribute; 228, 229; 228, 230; 229, identifier:results; 230, identifier:add_pid; 231, argument_list; 231, 232; 231, 233; 231, 234; 231, 239; 232, identifier:qname; 233, identifier:sname; 234, binary_operator:*; 234, 235; 234, 236; 235, float:0.01; 236, subscript; 236, 237; 236, 238; 237, identifier:resultvals; 238, integer:2; 239, keyword_argument; 239, 240; 239, 241; 240, identifier:sym; 241, False; 242, expression_statement; 242, 243; 243, call; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:results; 246, identifier:add_coverage; 247, argument_list; 247, 248; 247, 249; 247, 250; 248, identifier:qname; 249, identifier:sname; 250, identifier:query_cover; 251, return_statement; 251, 252; 252, identifier:results
def process_blast( blast_dir, org_lengths, fraglengths=None, mode="ANIb", identity=0.3, coverage=0.7, logger=None, ): """Returns a tuple of ANIb results for .blast_tab files in the output dir. - blast_dir - path to the directory containing .blast_tab files - org_lengths - the base count for each input sequence - fraglengths - dictionary of query sequence fragment lengths, only needed for BLASTALL output - mode - parsing BLASTN+ or BLASTALL output? - logger - a logger for messages Returns the following pandas dataframes in an ANIResults object; query sequences are rows, subject sequences are columns: - alignment_lengths - non-symmetrical: total length of alignment - percentage_identity - non-symmetrical: ANIb (Goris) percentage identity - alignment_coverage - non-symmetrical: coverage of query - similarity_errors - non-symmetrical: count of similarity errors May throw a ZeroDivisionError if one or more BLAST runs failed, or a very distant sequence was included in the analysis. """ # Process directory to identify input files blastfiles = pyani_files.get_input_files(blast_dir, ".blast_tab") # Hold data in ANIResults object results = ANIResults(list(org_lengths.keys()), mode) # Fill diagonal NA values for alignment_length with org_lengths for org, length in list(org_lengths.items()): results.alignment_lengths[org][org] = length # Process .blast_tab files assuming that the filename format holds: # org1_vs_org2.blast_tab: for blastfile in blastfiles: qname, sname = os.path.splitext(os.path.split(blastfile)[-1])[0].split("_vs_") # We may have BLAST files from other analyses in the same directory # If this occurs, we raise a warning, and skip the file if qname not in list(org_lengths.keys()): if logger: logger.warning( "Query name %s not in input " % qname + "sequence list, skipping %s" % blastfile ) continue if sname not in list(org_lengths.keys()): if logger: logger.warning( "Subject name %s not in input " % sname + "sequence list, skipping %s" % blastfile ) continue resultvals = parse_blast_tab(blastfile, fraglengths, identity, coverage, mode) query_cover = float(resultvals[0]) / org_lengths[qname] # Populate dataframes: when assigning data, we need to note that # we have asymmetrical data from BLAST output, so only the # upper triangle is populated results.add_tot_length(qname, sname, resultvals[0], sym=False) results.add_sim_errors(qname, sname, resultvals[1], sym=False) results.add_pid(qname, sname, 0.01 * resultvals[2], sym=False) results.add_coverage(qname, sname, query_cover) return results
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 17; 2, function_name:run_dependency_graph; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 4, identifier:jobgraph; 5, default_parameter; 5, 6; 5, 7; 6, identifier:logger; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:jgprefix; 10, string:"ANIm_SGE_JG"; 11, default_parameter; 11, 12; 11, 13; 12, identifier:sgegroupsize; 13, integer:10000; 14, default_parameter; 14, 15; 14, 16; 15, identifier:sgeargs; 16, None; 17, block; 17, 18; 17, 20; 17, 27; 17, 28; 17, 32; 17, 33; 17, 98; 17, 107; 17, 108; 17, 109; 17, 110; 17, 131; 17, 132; 17, 139; 17, 146; 17, 161; 17, 170; 17, 177; 18, expression_statement; 18, 19; 19, comment; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:joblist; 23, call; 23, 24; 23, 25; 24, identifier:build_joblist; 25, argument_list; 25, 26; 26, identifier:jobgraph; 27, comment; 28, expression_statement; 28, 29; 29, assignment; 29, 30; 29, 31; 30, identifier:dep_count; 31, integer:0; 32, comment; 33, if_statement; 33, 34; 33, 35; 34, identifier:logger; 35, block; 35, 36; 35, 43; 36, expression_statement; 36, 37; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:logger; 40, identifier:info; 41, argument_list; 41, 42; 42, string:"Jobs to run with scheduler"; 43, for_statement; 43, 44; 43, 45; 43, 46; 44, identifier:job; 45, identifier:joblist; 46, block; 46, 47; 46, 64; 47, expression_statement; 47, 48; 48, call; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:logger; 51, identifier:info; 52, argument_list; 52, 53; 53, call; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, string:"{0}: {1}"; 56, identifier:format; 57, argument_list; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:job; 60, identifier:name; 61, attribute; 61, 62; 61, 63; 62, identifier:job; 63, identifier:command; 64, if_statement; 64, 65; 64, 71; 65, call; 65, 66; 65, 67; 66, identifier:len; 67, argument_list; 67, 68; 68, attribute; 68, 69; 68, 70; 69, identifier:job; 70, identifier:dependencies; 71, block; 71, 72; 71, 81; 72, expression_statement; 72, 73; 73, augmented_assignment:+=; 73, 74; 73, 75; 74, identifier:dep_count; 75, call; 75, 76; 75, 77; 76, identifier:len; 77, argument_list; 77, 78; 78, attribute; 78, 79; 78, 80; 79, identifier:job; 80, identifier:dependencies; 81, for_statement; 81, 82; 81, 83; 81, 86; 82, identifier:dep; 83, attribute; 83, 84; 83, 85; 84, identifier:job; 85, identifier:dependencies; 86, block; 86, 87; 87, expression_statement; 87, 88; 88, call; 88, 89; 88, 92; 89, attribute; 89, 90; 89, 91; 90, identifier:logger; 91, identifier:info; 92, argument_list; 92, 93; 93, binary_operator:%; 93, 94; 93, 95; 94, string:"\t[^ depends on: %s]"; 95, attribute; 95, 96; 95, 97; 96, identifier:dep; 97, identifier:name; 98, expression_statement; 98, 99; 99, call; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:logger; 102, identifier:info; 103, argument_list; 103, 104; 104, binary_operator:%; 104, 105; 104, 106; 105, string:"There are %d job dependencies"; 106, identifier:dep_count; 107, comment; 108, comment; 109, comment; 110, if_statement; 110, 111; 110, 114; 111, comparison_operator:==; 111, 112; 111, 113; 112, identifier:dep_count; 113, integer:0; 114, block; 114, 115; 114, 122; 115, expression_statement; 115, 116; 116, call; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:logger; 119, identifier:info; 120, argument_list; 120, 121; 121, string:"Compiling jobs into JobGroups"; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:joblist; 125, call; 125, 126; 125, 127; 126, identifier:compile_jobgroups_from_joblist; 127, argument_list; 127, 128; 127, 129; 127, 130; 128, identifier:joblist; 129, identifier:jgprefix; 130, identifier:sgegroupsize; 131, comment; 132, expression_statement; 132, 133; 133, call; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:logger; 136, identifier:info; 137, argument_list; 137, 138; 138, string:"Running jobs with scheduler..."; 139, expression_statement; 139, 140; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:logger; 143, identifier:info; 144, argument_list; 144, 145; 145, string:"Jobs passed to scheduler in order:"; 146, for_statement; 146, 147; 146, 148; 146, 149; 147, identifier:job; 148, identifier:joblist; 149, block; 149, 150; 150, expression_statement; 150, 151; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:logger; 154, identifier:info; 155, argument_list; 155, 156; 156, binary_operator:%; 156, 157; 156, 158; 157, string:"\t%s"; 158, attribute; 158, 159; 158, 160; 159, identifier:job; 160, identifier:name; 161, expression_statement; 161, 162; 162, call; 162, 163; 162, 164; 163, identifier:build_and_submit_jobs; 164, argument_list; 164, 165; 164, 168; 164, 169; 165, attribute; 165, 166; 165, 167; 166, identifier:os; 167, identifier:curdir; 168, identifier:joblist; 169, identifier:sgeargs; 170, expression_statement; 170, 171; 171, call; 171, 172; 171, 175; 172, attribute; 172, 173; 172, 174; 173, identifier:logger; 174, identifier:info; 175, argument_list; 175, 176; 176, string:"Waiting for SGE-submitted jobs to finish (polling)"; 177, for_statement; 177, 178; 177, 179; 177, 180; 178, identifier:job; 179, identifier:joblist; 180, block; 180, 181; 181, expression_statement; 181, 182; 182, call; 182, 183; 182, 186; 183, attribute; 183, 184; 183, 185; 184, identifier:job; 185, identifier:wait; 186, argument_list
def run_dependency_graph(jobgraph, logger=None, jgprefix="ANIm_SGE_JG", sgegroupsize=10000, sgeargs=None): """Creates and runs GridEngine scripts for jobs based on the passed jobgraph. - jobgraph - list of jobs, which may have dependencies. - verbose - flag for multiprocessing verbosity - logger - a logger module logger (optional) - jgprefix - a prefix for the submitted jobs, in the scheduler - sgegroupsize - the maximum size for an array job submission - sgeargs - additional arguments to qsub The strategy here is to loop over each job in the list of jobs (jobgraph), and create/populate a series of Sets of commands, to be run in reverse order with multiprocessing_run as asynchronous pools. The strategy here is to loop over each job in the dependency graph, and add the job to a new list of jobs, swapping out the Job dependency for the name of the Job on which it depends. """ joblist = build_joblist(jobgraph) # Try to be informative by telling the user what jobs will run dep_count = 0 # how many dependencies are there if logger: logger.info("Jobs to run with scheduler") for job in joblist: logger.info("{0}: {1}".format(job.name, job.command)) if len(job.dependencies): dep_count += len(job.dependencies) for dep in job.dependencies: logger.info("\t[^ depends on: %s]" % dep.name) logger.info("There are %d job dependencies" % dep_count) # If there are no job dependencies, we can use an array (or series of # arrays) to schedule our jobs. This cuts down on problems with long # job lists choking up the queue. if dep_count == 0: logger.info("Compiling jobs into JobGroups") joblist = compile_jobgroups_from_joblist(joblist, jgprefix, sgegroupsize) # Send jobs to scheduler logger.info("Running jobs with scheduler...") logger.info("Jobs passed to scheduler in order:") for job in joblist: logger.info("\t%s" % job.name) build_and_submit_jobs(os.curdir, joblist, sgeargs) logger.info("Waiting for SGE-submitted jobs to finish (polling)") for job in joblist: job.wait()
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 21; 2, function_name:outputpairedstats; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 3, 11; 3, 12; 3, 13; 3, 14; 3, 15; 3, 16; 3, 17; 3, 18; 3, 19; 3, 20; 4, identifier:fname; 5, identifier:writemode; 6, identifier:name1; 7, identifier:n1; 8, identifier:m1; 9, identifier:se1; 10, identifier:min1; 11, identifier:max1; 12, identifier:name2; 13, identifier:n2; 14, identifier:m2; 15, identifier:se2; 16, identifier:min2; 17, identifier:max2; 18, identifier:statname; 19, identifier:stat; 20, identifier:prob; 21, block; 21, 22; 21, 24; 21, 28; 21, 29; 21, 46; 21, 73; 21, 84; 21, 130; 21, 326; 22, expression_statement; 22, 23; 23, comment; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:suffix; 27, string:''; 28, comment; 29, try_statement; 29, 30; 29, 43; 30, block; 30, 31; 30, 37; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:x; 34, attribute; 34, 35; 34, 36; 35, identifier:prob; 36, identifier:shape; 37, expression_statement; 37, 38; 38, assignment; 38, 39; 38, 40; 39, identifier:prob; 40, subscript; 40, 41; 40, 42; 41, identifier:prob; 42, integer:0; 43, except_clause; 43, 44; 44, block; 44, 45; 45, pass_statement; 46, if_statement; 46, 47; 46, 50; 46, 55; 46, 64; 47, comparison_operator:<; 47, 48; 47, 49; 48, identifier:prob; 49, float:0.001; 50, block; 50, 51; 51, expression_statement; 51, 52; 52, assignment; 52, 53; 52, 54; 53, identifier:suffix; 54, string:' ***'; 55, elif_clause; 55, 56; 55, 59; 56, comparison_operator:<; 56, 57; 56, 58; 57, identifier:prob; 58, float:0.01; 59, block; 59, 60; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:suffix; 63, string:' **'; 64, elif_clause; 64, 65; 64, 68; 65, comparison_operator:<; 65, 66; 65, 67; 66, identifier:prob; 67, float:0.05; 68, block; 68, 69; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:suffix; 72, string:' *'; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:title; 76, list:[['Name','N','Mean','SD','Min','Max']]; 76, 77; 77, list:['Name','N','Mean','SD','Min','Max']; 77, 78; 77, 79; 77, 80; 77, 81; 77, 82; 77, 83; 78, string:'Name'; 79, string:'N'; 80, string:'Mean'; 81, string:'SD'; 82, string:'Min'; 83, string:'Max'; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 87; 86, identifier:lofl; 87, binary_operator:+; 87, 88; 87, 89; 88, identifier:title; 89, list:[[name1,n1,round(m1,3),round(math.sqrt(se1),3),min1,max1], [name2,n2,round(m2,3),round(math.sqrt(se2),3),min2,max2]]; 89, 90; 89, 110; 90, list:[name1,n1,round(m1,3),round(math.sqrt(se1),3),min1,max1]; 90, 91; 90, 92; 90, 93; 90, 98; 90, 108; 90, 109; 91, identifier:name1; 92, identifier:n1; 93, call; 93, 94; 93, 95; 94, identifier:round; 95, argument_list; 95, 96; 95, 97; 96, identifier:m1; 97, integer:3; 98, call; 98, 99; 98, 100; 99, identifier:round; 100, argument_list; 100, 101; 100, 107; 101, call; 101, 102; 101, 105; 102, attribute; 102, 103; 102, 104; 103, identifier:math; 104, identifier:sqrt; 105, argument_list; 105, 106; 106, identifier:se1; 107, integer:3; 108, identifier:min1; 109, identifier:max1; 110, list:[name2,n2,round(m2,3),round(math.sqrt(se2),3),min2,max2]; 110, 111; 110, 112; 110, 113; 110, 118; 110, 128; 110, 129; 111, identifier:name2; 112, identifier:n2; 113, call; 113, 114; 113, 115; 114, identifier:round; 115, argument_list; 115, 116; 115, 117; 116, identifier:m2; 117, integer:3; 118, call; 118, 119; 118, 120; 119, identifier:round; 120, argument_list; 120, 121; 120, 127; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:math; 124, identifier:sqrt; 125, argument_list; 125, 126; 126, identifier:se2; 127, integer:3; 128, identifier:min2; 129, identifier:max2; 130, if_statement; 130, 131; 130, 144; 130, 221; 131, boolean_operator:or; 131, 132; 131, 138; 132, comparison_operator:!=; 132, 133; 132, 137; 133, call; 133, 134; 133, 135; 134, identifier:type; 135, argument_list; 135, 136; 136, identifier:fname; 137, identifier:StringType; 138, comparison_operator:==; 138, 139; 138, 143; 139, call; 139, 140; 139, 141; 140, identifier:len; 141, argument_list; 141, 142; 142, identifier:fname; 143, integer:0; 144, block; 144, 145; 144, 149; 144, 154; 144, 158; 144, 165; 144, 169; 144, 200; 144, 217; 145, expression_statement; 145, 146; 146, call; 146, 147; 146, 148; 147, identifier:print; 148, argument_list; 149, expression_statement; 149, 150; 150, call; 150, 151; 150, 152; 151, identifier:print; 152, argument_list; 152, 153; 153, identifier:statname; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 157; 156, identifier:print; 157, argument_list; 158, expression_statement; 158, 159; 159, call; 159, 160; 159, 163; 160, attribute; 160, 161; 160, 162; 161, identifier:pstat; 162, identifier:printcc; 163, argument_list; 163, 164; 164, identifier:lofl; 165, expression_statement; 165, 166; 166, call; 166, 167; 166, 168; 167, identifier:print; 168, argument_list; 169, try_statement; 169, 170; 169, 197; 170, block; 170, 171; 170, 184; 171, if_statement; 171, 172; 171, 177; 172, comparison_operator:==; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, identifier:stat; 175, identifier:shape; 176, tuple; 177, block; 177, 178; 178, expression_statement; 178, 179; 179, assignment; 179, 180; 179, 181; 180, identifier:stat; 181, subscript; 181, 182; 181, 183; 182, identifier:stat; 183, integer:0; 184, if_statement; 184, 185; 184, 190; 185, comparison_operator:==; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:prob; 188, identifier:shape; 189, tuple; 190, block; 190, 191; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:prob; 194, subscript; 194, 195; 194, 196; 195, identifier:prob; 196, integer:0; 197, except_clause; 197, 198; 198, block; 198, 199; 199, pass_statement; 200, expression_statement; 200, 201; 201, call; 201, 202; 201, 203; 202, identifier:print; 203, argument_list; 203, 204; 203, 205; 203, 210; 203, 211; 203, 216; 204, string:'Test statistic = '; 205, call; 205, 206; 205, 207; 206, identifier:round; 207, argument_list; 207, 208; 207, 209; 208, identifier:stat; 209, integer:3; 210, string:' p = '; 211, call; 211, 212; 211, 213; 212, identifier:round; 213, argument_list; 213, 214; 213, 215; 214, identifier:prob; 215, integer:3; 216, identifier:suffix; 217, expression_statement; 217, 218; 218, call; 218, 219; 218, 220; 219, identifier:print; 220, argument_list; 221, else_clause; 221, 222; 222, block; 222, 223; 222, 231; 222, 242; 222, 248; 222, 255; 222, 263; 222, 294; 222, 320; 223, expression_statement; 223, 224; 224, assignment; 224, 225; 224, 226; 225, identifier:file; 226, call; 226, 227; 226, 228; 227, identifier:open; 228, argument_list; 228, 229; 228, 230; 229, identifier:fname; 230, identifier:writemode; 231, expression_statement; 231, 232; 232, call; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:file; 235, identifier:write; 236, argument_list; 236, 237; 237, binary_operator:+; 237, 238; 237, 241; 238, binary_operator:+; 238, 239; 238, 240; 239, string:'\n'; 240, identifier:statname; 241, string:'\n\n'; 242, expression_statement; 242, 243; 243, call; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:file; 246, identifier:close; 247, argument_list; 248, expression_statement; 248, 249; 249, call; 249, 250; 249, 251; 250, identifier:writecc; 251, argument_list; 251, 252; 251, 253; 251, 254; 252, identifier:lofl; 253, identifier:fname; 254, string:'a'; 255, expression_statement; 255, 256; 256, assignment; 256, 257; 256, 258; 257, identifier:file; 258, call; 258, 259; 258, 260; 259, identifier:open; 260, argument_list; 260, 261; 260, 262; 261, identifier:fname; 262, string:'a'; 263, try_statement; 263, 264; 263, 291; 264, block; 264, 265; 264, 278; 265, if_statement; 265, 266; 265, 271; 266, comparison_operator:==; 266, 267; 266, 270; 267, attribute; 267, 268; 267, 269; 268, identifier:stat; 269, identifier:shape; 270, tuple; 271, block; 271, 272; 272, expression_statement; 272, 273; 273, assignment; 273, 274; 273, 275; 274, identifier:stat; 275, subscript; 275, 276; 275, 277; 276, identifier:stat; 277, integer:0; 278, if_statement; 278, 279; 278, 284; 279, comparison_operator:==; 279, 280; 279, 283; 280, attribute; 280, 281; 280, 282; 281, identifier:prob; 282, identifier:shape; 283, tuple; 284, block; 284, 285; 285, expression_statement; 285, 286; 286, assignment; 286, 287; 286, 288; 287, identifier:prob; 288, subscript; 288, 289; 288, 290; 289, identifier:prob; 290, integer:0; 291, except_clause; 291, 292; 292, block; 292, 293; 293, pass_statement; 294, expression_statement; 294, 295; 295, call; 295, 296; 295, 299; 296, attribute; 296, 297; 296, 298; 297, identifier:file; 298, identifier:write; 299, argument_list; 299, 300; 300, call; 300, 301; 300, 304; 301, attribute; 301, 302; 301, 303; 302, identifier:pstat; 303, identifier:list2string; 304, argument_list; 304, 305; 305, list:['\nTest statistic = ',round(stat,4),' p = ',round(prob,4),suffix,'\n\n']; 305, 306; 305, 307; 305, 312; 305, 313; 305, 318; 305, 319; 306, string:'\nTest statistic = '; 307, call; 307, 308; 307, 309; 308, identifier:round; 309, argument_list; 309, 310; 309, 311; 310, identifier:stat; 311, integer:4; 312, string:' p = '; 313, call; 313, 314; 313, 315; 314, identifier:round; 315, argument_list; 315, 316; 315, 317; 316, identifier:prob; 317, integer:4; 318, identifier:suffix; 319, string:'\n\n'; 320, expression_statement; 320, 321; 321, call; 321, 322; 321, 325; 322, attribute; 322, 323; 322, 324; 323, identifier:file; 324, identifier:close; 325, argument_list; 326, return_statement; 326, 327; 327, None
def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob): """ Prints or write to a file stats for two groups, using the name, n, mean, sterr, min and max for each group, as well as the statistic name, its value, and the associated p-value. Usage: outputpairedstats(fname,writemode, name1,n1,mean1,stderr1,min1,max1, name2,n2,mean2,stderr2,min2,max2, statname,stat,prob) Returns: None """ suffix = '' # for *s after the p-value try: x = prob.shape prob = prob[0] except: pass if prob < 0.001: suffix = ' ***' elif prob < 0.01: suffix = ' **' elif prob < 0.05: suffix = ' *' title = [['Name','N','Mean','SD','Min','Max']] lofl = title+[[name1,n1,round(m1,3),round(math.sqrt(se1),3),min1,max1], [name2,n2,round(m2,3),round(math.sqrt(se2),3),min2,max2]] if type(fname)!=StringType or len(fname)==0: print() print(statname) print() pstat.printcc(lofl) print() try: if stat.shape == (): stat = stat[0] if prob.shape == (): prob = prob[0] except: pass print('Test statistic = ',round(stat,3),' p = ',round(prob,3),suffix) print() else: file = open(fname,writemode) file.write('\n'+statname+'\n\n') file.close() writecc(lofl,fname,'a') file = open(fname,'a') try: if stat.shape == (): stat = stat[0] if prob.shape == (): prob = prob[0] except: pass file.write(pstat.list2string(['\nTest statistic = ',round(stat,4),' p = ',round(prob,4),suffix,'\n\n'])) file.close() return None
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:GeneReader; 3, parameters; 3, 4; 3, 5; 4, identifier:fh; 5, default_parameter; 5, 6; 5, 7; 6, identifier:format; 7, string:'gff'; 8, block; 8, 9; 8, 11; 8, 18; 8, 47; 8, 211; 8, 215; 8, 219; 9, expression_statement; 9, 10; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:known_formats; 14, tuple; 14, 15; 14, 16; 14, 17; 15, string:'gff'; 16, string:'gtf'; 17, string:'bed'; 18, if_statement; 18, 19; 18, 22; 19, comparison_operator:not; 19, 20; 19, 21; 20, identifier:format; 21, identifier:known_formats; 22, block; 22, 23; 22, 42; 23, expression_statement; 23, 24; 24, call; 24, 25; 24, 26; 25, identifier:print; 26, argument_list; 26, 27; 26, 37; 27, binary_operator:%; 27, 28; 27, 29; 28, string:'%s format not in %s'; 29, tuple; 29, 30; 29, 31; 30, identifier:format; 31, call; 31, 32; 31, 35; 32, attribute; 32, 33; 32, 34; 33, string:","; 34, identifier:join; 35, argument_list; 35, 36; 36, identifier:known_formats; 37, keyword_argument; 37, 38; 37, 39; 38, identifier:file; 39, attribute; 39, 40; 39, 41; 40, identifier:sys; 41, identifier:stderr; 42, raise_statement; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:Exception; 45, argument_list; 45, 46; 46, string:'?'; 47, if_statement; 47, 48; 47, 51; 48, comparison_operator:==; 48, 49; 48, 50; 49, identifier:format; 50, string:'bed'; 51, block; 51, 52; 52, for_statement; 52, 53; 52, 54; 52, 55; 53, identifier:line; 54, identifier:fh; 55, block; 55, 56; 55, 68; 55, 74; 55, 83; 55, 89; 55, 95; 55, 104; 55, 113; 55, 122; 55, 145; 55, 170; 55, 171; 55, 175; 55, 204; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 59; 58, identifier:f; 59, call; 59, 60; 59, 67; 60, attribute; 60, 61; 60, 66; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:line; 64, identifier:strip; 65, argument_list; 66, identifier:split; 67, argument_list; 68, expression_statement; 68, 69; 69, assignment; 69, 70; 69, 71; 70, identifier:chrom; 71, subscript; 71, 72; 71, 73; 72, identifier:f; 73, integer:0; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:chrom_start; 77, call; 77, 78; 77, 79; 78, identifier:int; 79, argument_list; 79, 80; 80, subscript; 80, 81; 80, 82; 81, identifier:f; 82, integer:1; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:name; 86, subscript; 86, 87; 86, 88; 87, identifier:f; 88, integer:4; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:strand; 92, subscript; 92, 93; 92, 94; 93, identifier:f; 94, integer:5; 95, expression_statement; 95, 96; 96, assignment; 96, 97; 96, 98; 97, identifier:cdsStart; 98, call; 98, 99; 98, 100; 99, identifier:int; 100, argument_list; 100, 101; 101, subscript; 101, 102; 101, 103; 102, identifier:f; 103, integer:6; 104, expression_statement; 104, 105; 105, assignment; 105, 106; 105, 107; 106, identifier:cdsEnd; 107, call; 107, 108; 107, 109; 108, identifier:int; 109, argument_list; 109, 110; 110, subscript; 110, 111; 110, 112; 111, identifier:f; 112, integer:7; 113, expression_statement; 113, 114; 114, assignment; 114, 115; 114, 116; 115, identifier:blockCount; 116, call; 116, 117; 116, 118; 117, identifier:int; 118, argument_list; 118, 119; 119, subscript; 119, 120; 119, 121; 120, identifier:f; 121, integer:9; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:blockSizes; 125, list_comprehension; 125, 126; 125, 130; 126, call; 126, 127; 126, 128; 127, identifier:int; 128, argument_list; 128, 129; 129, identifier:i; 130, for_in_clause; 130, 131; 130, 132; 131, identifier:i; 132, call; 132, 133; 132, 143; 133, attribute; 133, 134; 133, 142; 134, call; 134, 135; 134, 140; 135, attribute; 135, 136; 135, 139; 136, subscript; 136, 137; 136, 138; 137, identifier:f; 138, integer:10; 139, identifier:strip; 140, argument_list; 140, 141; 141, string:','; 142, identifier:split; 143, argument_list; 143, 144; 144, string:','; 145, expression_statement; 145, 146; 146, assignment; 146, 147; 146, 148; 147, identifier:blockStarts; 148, list_comprehension; 148, 149; 148, 155; 149, binary_operator:+; 149, 150; 149, 151; 150, identifier:chrom_start; 151, call; 151, 152; 151, 153; 152, identifier:int; 153, argument_list; 153, 154; 154, identifier:i; 155, for_in_clause; 155, 156; 155, 157; 156, identifier:i; 157, call; 157, 158; 157, 168; 158, attribute; 158, 159; 158, 167; 159, call; 159, 160; 159, 165; 160, attribute; 160, 161; 160, 164; 161, subscript; 161, 162; 161, 163; 162, identifier:f; 163, integer:11; 164, identifier:strip; 165, argument_list; 165, 166; 166, string:','; 167, identifier:split; 168, argument_list; 168, 169; 169, string:','; 170, comment; 171, expression_statement; 171, 172; 172, assignment; 172, 173; 172, 174; 173, identifier:gene_exons; 174, list:[]; 175, for_statement; 175, 176; 175, 179; 175, 184; 176, pattern_list; 176, 177; 176, 178; 177, identifier:base; 178, identifier:offset; 179, call; 179, 180; 179, 181; 180, identifier:zip; 181, argument_list; 181, 182; 181, 183; 182, identifier:blockStarts; 183, identifier:blockSizes; 184, block; 184, 185; 184, 189; 184, 195; 185, expression_statement; 185, 186; 186, assignment; 186, 187; 186, 188; 187, identifier:exon_start; 188, identifier:base; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 192; 191, identifier:exon_end; 192, binary_operator:+; 192, 193; 192, 194; 193, identifier:base; 194, identifier:offset; 195, expression_statement; 195, 196; 196, call; 196, 197; 196, 200; 197, attribute; 197, 198; 197, 199; 198, identifier:gene_exons; 199, identifier:append; 200, argument_list; 200, 201; 201, tuple; 201, 202; 201, 203; 202, identifier:exon_start; 203, identifier:exon_end; 204, expression_statement; 204, 205; 205, yield; 205, 206; 206, expression_list; 206, 207; 206, 208; 206, 209; 206, 210; 207, identifier:chrom; 208, identifier:strand; 209, identifier:gene_exons; 210, identifier:name; 211, expression_statement; 211, 212; 212, assignment; 212, 213; 212, 214; 213, identifier:genelist; 214, dictionary; 215, expression_statement; 215, 216; 216, assignment; 216, 217; 216, 218; 217, identifier:grouplist; 218, list:[]; 219, if_statement; 219, 220; 219, 227; 220, boolean_operator:or; 220, 221; 220, 224; 221, comparison_operator:==; 221, 222; 221, 223; 222, identifier:format; 223, string:'gff'; 224, comparison_operator:==; 224, 225; 224, 226; 225, identifier:format; 226, string:'gtf'; 227, block; 227, 228; 227, 367; 227, 383; 227, 384; 228, for_statement; 228, 229; 228, 230; 228, 231; 229, identifier:line; 230, identifier:fh; 231, block; 231, 232; 231, 241; 231, 254; 231, 263; 231, 264; 231, 270; 231, 281; 231, 282; 231, 291; 231, 292; 231, 298; 231, 324; 231, 336; 231, 350; 231, 354; 232, if_statement; 232, 233; 232, 239; 233, call; 233, 234; 233, 237; 234, attribute; 234, 235; 234, 236; 235, identifier:line; 236, identifier:startswith; 237, argument_list; 237, 238; 238, string:'#'; 239, block; 239, 240; 240, continue_statement; 241, expression_statement; 241, 242; 242, assignment; 242, 243; 242, 244; 243, identifier:fields; 244, call; 244, 245; 244, 252; 245, attribute; 245, 246; 245, 251; 246, call; 246, 247; 246, 250; 247, attribute; 247, 248; 247, 249; 248, identifier:line; 249, identifier:strip; 250, argument_list; 251, identifier:split; 252, argument_list; 252, 253; 253, string:'\t'; 254, if_statement; 254, 255; 254, 261; 255, comparison_operator:<; 255, 256; 255, 260; 256, call; 256, 257; 256, 258; 257, identifier:len; 258, argument_list; 258, 259; 259, identifier:fields; 260, integer:9; 261, block; 261, 262; 262, continue_statement; 263, comment; 264, expression_statement; 264, 265; 265, assignment; 265, 266; 265, 267; 266, identifier:chrom; 267, subscript; 267, 268; 267, 269; 268, identifier:fields; 269, integer:0; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:ex_st; 273, binary_operator:-; 273, 274; 273, 280; 274, call; 274, 275; 274, 276; 275, identifier:int; 276, argument_list; 276, 277; 277, subscript; 277, 278; 277, 279; 278, identifier:fields; 279, integer:3; 280, integer:1; 281, comment; 282, expression_statement; 282, 283; 283, assignment; 283, 284; 283, 285; 284, identifier:ex_end; 285, call; 285, 286; 285, 287; 286, identifier:int; 287, argument_list; 287, 288; 288, subscript; 288, 289; 288, 290; 289, identifier:fields; 290, integer:4; 291, comment; 292, expression_statement; 292, 293; 293, assignment; 293, 294; 293, 295; 294, identifier:strand; 295, subscript; 295, 296; 295, 297; 296, identifier:fields; 297, integer:6; 298, if_statement; 298, 299; 298, 302; 298, 316; 299, comparison_operator:==; 299, 300; 299, 301; 300, identifier:format; 301, string:'gtf'; 302, block; 302, 303; 303, expression_statement; 303, 304; 304, assignment; 304, 305; 304, 306; 305, identifier:group; 306, subscript; 306, 307; 306, 315; 307, call; 307, 308; 307, 313; 308, attribute; 308, 309; 308, 312; 309, subscript; 309, 310; 309, 311; 310, identifier:fields; 311, integer:8; 312, identifier:split; 313, argument_list; 313, 314; 314, string:';'; 315, integer:0; 316, else_clause; 316, 317; 317, block; 317, 318; 318, expression_statement; 318, 319; 319, assignment; 319, 320; 319, 321; 320, identifier:group; 321, subscript; 321, 322; 321, 323; 322, identifier:fields; 323, integer:8; 324, if_statement; 324, 325; 324, 328; 325, comparison_operator:not; 325, 326; 325, 327; 326, identifier:group; 327, identifier:grouplist; 328, block; 328, 329; 329, expression_statement; 329, 330; 330, call; 330, 331; 330, 334; 331, attribute; 331, 332; 331, 333; 332, identifier:grouplist; 333, identifier:append; 334, argument_list; 334, 335; 335, identifier:group; 336, if_statement; 336, 337; 336, 340; 337, comparison_operator:not; 337, 338; 337, 339; 338, identifier:group; 339, identifier:genelist; 340, block; 340, 341; 341, expression_statement; 341, 342; 342, assignment; 342, 343; 342, 346; 343, subscript; 343, 344; 343, 345; 344, identifier:genelist; 345, identifier:group; 346, tuple; 346, 347; 346, 348; 346, 349; 347, identifier:chrom; 348, identifier:strand; 349, list:[]; 350, expression_statement; 350, 351; 351, assignment; 351, 352; 351, 353; 352, identifier:exons_i; 353, integer:2; 354, expression_statement; 354, 355; 355, call; 355, 356; 355, 363; 356, attribute; 356, 357; 356, 362; 357, subscript; 357, 358; 357, 361; 358, subscript; 358, 359; 358, 360; 359, identifier:genelist; 360, identifier:group; 361, identifier:exons_i; 362, identifier:append; 363, argument_list; 363, 364; 364, tuple; 364, 365; 364, 366; 365, identifier:ex_st; 366, identifier:ex_end; 367, expression_statement; 367, 368; 368, assignment; 368, 369; 368, 370; 369, identifier:sp; 370, lambda; 370, 371; 370, 374; 371, lambda_parameters; 371, 372; 371, 373; 372, identifier:a; 373, identifier:b; 374, call; 374, 375; 374, 376; 375, identifier:cmp; 376, argument_list; 376, 377; 376, 380; 377, subscript; 377, 378; 377, 379; 378, identifier:a; 379, integer:0; 380, subscript; 380, 381; 380, 382; 381, identifier:b; 382, integer:0; 383, comment; 384, for_statement; 384, 385; 384, 386; 384, 387; 385, identifier:gene; 386, identifier:grouplist; 387, block; 387, 388; 387, 397; 387, 404; 388, expression_statement; 388, 389; 389, assignment; 389, 390; 389, 394; 390, pattern_list; 390, 391; 390, 392; 390, 393; 391, identifier:chrom; 392, identifier:strand; 393, identifier:gene_exons; 394, subscript; 394, 395; 394, 396; 395, identifier:genelist; 396, identifier:gene; 397, expression_statement; 397, 398; 398, assignment; 398, 399; 398, 400; 399, identifier:gene_exons; 400, call; 400, 401; 400, 402; 401, identifier:bitset_union; 402, argument_list; 402, 403; 403, identifier:gene_exons; 404, expression_statement; 404, 405; 405, yield; 405, 406; 406, expression_list; 406, 407; 406, 408; 406, 409; 406, 410; 407, identifier:chrom; 408, identifier:strand; 409, identifier:gene_exons; 410, identifier:gene
def GeneReader( fh, format='gff' ): """ yield chrom, strand, gene_exons, name """ known_formats = ( 'gff', 'gtf', 'bed') if format not in known_formats: print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr) raise Exception('?') if format == 'bed': for line in fh: f = line.strip().split() chrom = f[0] chrom_start = int(f[1]) name = f[4] strand = f[5] cdsStart = int(f[6]) cdsEnd = int(f[7]) blockCount = int(f[9]) blockSizes = [ int(i) for i in f[10].strip(',').split(',') ] blockStarts = [ chrom_start + int(i) for i in f[11].strip(',').split(',') ] # grab cdsStart - cdsEnd gene_exons = [] for base,offset in zip( blockStarts, blockSizes ): exon_start = base exon_end = base+offset gene_exons.append( (exon_start, exon_end) ) yield chrom, strand, gene_exons, name genelist = {} grouplist = [] if format == 'gff' or format == 'gtf': for line in fh: if line.startswith('#'): continue fields = line.strip().split('\t') if len( fields ) < 9: continue # fields chrom = fields[0] ex_st = int( fields[3] ) - 1 # make zero-centered ex_end = int( fields[4] ) #+ 1 # make exclusive strand = fields[6] if format == 'gtf': group = fields[8].split(';')[0] else: group = fields[8] if group not in grouplist: grouplist.append( group ) if group not in genelist: genelist[group] = (chrom, strand, []) exons_i = 2 genelist[group][exons_i].append( ( ex_st, ex_end ) ) sp = lambda a,b: cmp( a[0], b[0] ) #for gene in genelist.values(): for gene in grouplist: chrom, strand, gene_exons = genelist[ gene ] gene_exons = bitset_union( gene_exons ) yield chrom, strand, gene_exons, gene
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:read_next_maf; 3, parameters; 3, 4; 3, 5; 3, 8; 4, identifier:file; 5, default_parameter; 5, 6; 5, 7; 6, identifier:species_to_lengths; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:parse_e_rows; 10, False; 11, block; 11, 12; 11, 14; 11, 23; 11, 24; 11, 34; 11, 40; 11, 48; 11, 60; 11, 73; 11, 104; 11, 105; 11, 109; 11, 430; 12, expression_statement; 12, 13; 13, comment; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:alignment; 17, call; 17, 18; 17, 19; 18, identifier:Alignment; 19, argument_list; 19, 20; 20, keyword_argument; 20, 21; 20, 22; 21, identifier:species_to_lengths; 22, identifier:species_to_lengths; 23, comment; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:line; 27, call; 27, 28; 27, 29; 28, identifier:readline; 29, argument_list; 29, 30; 29, 31; 30, identifier:file; 31, keyword_argument; 31, 32; 31, 33; 32, identifier:skip_blank; 33, True; 34, if_statement; 34, 35; 34, 37; 35, not_operator; 35, 36; 36, identifier:line; 37, block; 37, 38; 38, return_statement; 38, 39; 39, None; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:fields; 43, call; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:line; 46, identifier:split; 47, argument_list; 48, if_statement; 48, 49; 48, 54; 49, comparison_operator:!=; 49, 50; 49, 53; 50, subscript; 50, 51; 50, 52; 51, identifier:fields; 52, integer:0; 53, string:'a'; 54, block; 54, 55; 55, raise_statement; 55, 56; 56, call; 56, 57; 56, 58; 57, identifier:Exception; 58, argument_list; 58, 59; 59, string:"Expected 'a ...' line"; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:alignment; 64, identifier:attributes; 65, call; 65, 66; 65, 67; 66, identifier:parse_attributes; 67, argument_list; 67, 68; 68, subscript; 68, 69; 68, 70; 69, identifier:fields; 70, slice; 70, 71; 70, 72; 71, integer:1; 72, colon; 73, if_statement; 73, 74; 73, 79; 73, 96; 74, comparison_operator:in; 74, 75; 74, 76; 75, string:'score'; 76, attribute; 76, 77; 76, 78; 77, identifier:alignment; 78, identifier:attributes; 79, block; 79, 80; 79, 90; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:alignment; 84, identifier:score; 85, subscript; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:alignment; 88, identifier:attributes; 89, string:'score'; 90, delete_statement; 90, 91; 91, subscript; 91, 92; 91, 95; 92, attribute; 92, 93; 92, 94; 93, identifier:alignment; 94, identifier:attributes; 95, string:'score'; 96, else_clause; 96, 97; 97, block; 97, 98; 98, expression_statement; 98, 99; 99, assignment; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:alignment; 102, identifier:score; 103, integer:0; 104, comment; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:last_component; 108, None; 109, while_statement; 109, 110; 109, 111; 110, integer:1; 111, block; 111, 112; 111, 119; 111, 120; 111, 131; 111, 139; 111, 140; 111, 148; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:line; 115, call; 115, 116; 115, 117; 116, identifier:readline; 117, argument_list; 117, 118; 118, identifier:file; 119, comment; 120, if_statement; 120, 121; 120, 129; 121, boolean_operator:or; 121, 122; 121, 124; 122, not_operator; 122, 123; 123, identifier:line; 124, call; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:line; 127, identifier:isspace; 128, argument_list; 129, block; 129, 130; 130, break_statement; 131, if_statement; 131, 132; 131, 137; 132, call; 132, 133; 132, 136; 133, attribute; 133, 134; 133, 135; 134, identifier:line; 135, identifier:isspace; 136, argument_list; 137, block; 137, 138; 138, break_statement; 139, comment; 140, expression_statement; 140, 141; 141, assignment; 141, 142; 141, 143; 142, identifier:fields; 143, call; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:line; 146, identifier:split; 147, argument_list; 148, if_statement; 148, 149; 148, 154; 148, 155; 148, 243; 148, 357; 148, 405; 149, comparison_operator:==; 149, 150; 149, 153; 150, subscript; 150, 151; 150, 152; 151, identifier:fields; 152, integer:0; 153, string:'s'; 154, comment; 155, block; 155, 156; 155, 162; 155, 170; 155, 181; 155, 192; 155, 200; 155, 211; 155, 231; 155, 232; 155, 239; 156, expression_statement; 156, 157; 157, assignment; 157, 158; 157, 159; 158, identifier:component; 159, call; 159, 160; 159, 161; 160, identifier:Component; 161, argument_list; 162, expression_statement; 162, 163; 163, assignment; 163, 164; 163, 167; 164, attribute; 164, 165; 164, 166; 165, identifier:component; 166, identifier:src; 167, subscript; 167, 168; 167, 169; 168, identifier:fields; 169, integer:1; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 175; 172, attribute; 172, 173; 172, 174; 173, identifier:component; 174, identifier:start; 175, call; 175, 176; 175, 177; 176, identifier:int; 177, argument_list; 177, 178; 178, subscript; 178, 179; 178, 180; 179, identifier:fields; 180, integer:2; 181, expression_statement; 181, 182; 182, assignment; 182, 183; 182, 186; 183, attribute; 183, 184; 183, 185; 184, identifier:component; 185, identifier:size; 186, call; 186, 187; 186, 188; 187, identifier:int; 188, argument_list; 188, 189; 189, subscript; 189, 190; 189, 191; 190, identifier:fields; 191, integer:3; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:component; 196, identifier:strand; 197, subscript; 197, 198; 197, 199; 198, identifier:fields; 199, integer:4; 200, expression_statement; 200, 201; 201, assignment; 201, 202; 201, 205; 202, attribute; 202, 203; 202, 204; 203, identifier:component; 204, identifier:src_size; 205, call; 205, 206; 205, 207; 206, identifier:int; 207, argument_list; 207, 208; 208, subscript; 208, 209; 208, 210; 209, identifier:fields; 210, integer:5; 211, if_statement; 211, 212; 211, 218; 212, comparison_operator:>; 212, 213; 212, 217; 213, call; 213, 214; 213, 215; 214, identifier:len; 215, argument_list; 215, 216; 216, identifier:fields; 217, integer:6; 218, block; 218, 219; 219, expression_statement; 219, 220; 220, assignment; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:component; 223, identifier:text; 224, call; 224, 225; 224, 230; 225, attribute; 225, 226; 225, 229; 226, subscript; 226, 227; 226, 228; 227, identifier:fields; 228, integer:6; 229, identifier:strip; 230, argument_list; 231, comment; 232, expression_statement; 232, 233; 233, call; 233, 234; 233, 237; 234, attribute; 234, 235; 234, 236; 235, identifier:alignment; 236, identifier:add_component; 237, argument_list; 237, 238; 238, identifier:component; 239, expression_statement; 239, 240; 240, assignment; 240, 241; 240, 242; 241, identifier:last_component; 242, identifier:component; 243, elif_clause; 243, 244; 243, 249; 243, 250; 243, 251; 244, comparison_operator:==; 244, 245; 244, 248; 245, subscript; 245, 246; 245, 247; 246, identifier:fields; 247, integer:0; 248, string:'e'; 249, comment; 250, comment; 251, block; 251, 252; 252, if_statement; 252, 253; 252, 254; 253, identifier:parse_e_rows; 254, block; 254, 255; 254, 261; 254, 267; 254, 275; 254, 286; 254, 297; 254, 305; 254, 316; 254, 322; 254, 332; 254, 340; 254, 346; 254, 353; 255, expression_statement; 255, 256; 256, assignment; 256, 257; 256, 258; 257, identifier:component; 258, call; 258, 259; 258, 260; 259, identifier:Component; 260, argument_list; 261, expression_statement; 261, 262; 262, assignment; 262, 263; 262, 266; 263, attribute; 263, 264; 263, 265; 264, identifier:component; 265, identifier:empty; 266, True; 267, expression_statement; 267, 268; 268, assignment; 268, 269; 268, 272; 269, attribute; 269, 270; 269, 271; 270, identifier:component; 271, identifier:src; 272, subscript; 272, 273; 272, 274; 273, identifier:fields; 274, integer:1; 275, expression_statement; 275, 276; 276, assignment; 276, 277; 276, 280; 277, attribute; 277, 278; 277, 279; 278, identifier:component; 279, identifier:start; 280, call; 280, 281; 280, 282; 281, identifier:int; 282, argument_list; 282, 283; 283, subscript; 283, 284; 283, 285; 284, identifier:fields; 285, integer:2; 286, expression_statement; 286, 287; 287, assignment; 287, 288; 287, 291; 288, attribute; 288, 289; 288, 290; 289, identifier:component; 290, identifier:size; 291, call; 291, 292; 291, 293; 292, identifier:int; 293, argument_list; 293, 294; 294, subscript; 294, 295; 294, 296; 295, identifier:fields; 296, integer:3; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 302; 299, attribute; 299, 300; 299, 301; 300, identifier:component; 301, identifier:strand; 302, subscript; 302, 303; 302, 304; 303, identifier:fields; 304, integer:4; 305, expression_statement; 305, 306; 306, assignment; 306, 307; 306, 310; 307, attribute; 307, 308; 307, 309; 308, identifier:component; 309, identifier:src_size; 310, call; 310, 311; 310, 312; 311, identifier:int; 312, argument_list; 312, 313; 313, subscript; 313, 314; 313, 315; 314, identifier:fields; 315, integer:5; 316, expression_statement; 316, 317; 317, assignment; 317, 318; 317, 321; 318, attribute; 318, 319; 318, 320; 319, identifier:component; 320, identifier:text; 321, None; 322, expression_statement; 322, 323; 323, assignment; 323, 324; 323, 325; 324, identifier:synteny; 325, call; 325, 326; 325, 331; 326, attribute; 326, 327; 326, 330; 327, subscript; 327, 328; 327, 329; 328, identifier:fields; 329, integer:6; 330, identifier:strip; 331, argument_list; 332, assert_statement; 332, 333; 332, 339; 333, comparison_operator:==; 333, 334; 333, 338; 334, call; 334, 335; 334, 336; 335, identifier:len; 336, argument_list; 336, 337; 337, identifier:synteny; 338, integer:1; 339, string:"Synteny status in 'e' rows should be denoted with a single character code"; 340, expression_statement; 340, 341; 341, assignment; 341, 342; 341, 345; 342, attribute; 342, 343; 342, 344; 343, identifier:component; 344, identifier:synteny_empty; 345, identifier:synteny; 346, expression_statement; 346, 347; 347, call; 347, 348; 347, 351; 348, attribute; 348, 349; 348, 350; 349, identifier:alignment; 350, identifier:add_component; 351, argument_list; 351, 352; 352, identifier:component; 353, expression_statement; 353, 354; 354, assignment; 354, 355; 354, 356; 355, identifier:last_component; 356, identifier:component; 357, elif_clause; 357, 358; 357, 363; 357, 364; 357, 365; 358, comparison_operator:==; 358, 359; 358, 362; 359, subscript; 359, 360; 359, 361; 360, identifier:fields; 361, integer:0; 362, string:'i'; 363, comment; 364, comment; 365, block; 365, 366; 365, 375; 365, 390; 366, assert_statement; 366, 367; 366, 374; 367, comparison_operator:==; 367, 368; 367, 371; 368, subscript; 368, 369; 368, 370; 369, identifier:fields; 370, integer:1; 371, attribute; 371, 372; 371, 373; 372, identifier:last_component; 373, identifier:src; 374, string:"'i' row does not follow matching 's' row"; 375, expression_statement; 375, 376; 376, assignment; 376, 377; 376, 380; 377, attribute; 377, 378; 377, 379; 378, identifier:last_component; 379, identifier:synteny_left; 380, tuple; 380, 381; 380, 384; 381, subscript; 381, 382; 381, 383; 382, identifier:fields; 383, integer:2; 384, call; 384, 385; 384, 386; 385, identifier:int; 386, argument_list; 386, 387; 387, subscript; 387, 388; 387, 389; 388, identifier:fields; 389, integer:3; 390, expression_statement; 390, 391; 391, assignment; 391, 392; 391, 395; 392, attribute; 392, 393; 392, 394; 393, identifier:last_component; 394, identifier:synteny_right; 395, tuple; 395, 396; 395, 399; 396, subscript; 396, 397; 396, 398; 397, identifier:fields; 398, integer:4; 399, call; 399, 400; 399, 401; 400, identifier:int; 401, argument_list; 401, 402; 402, subscript; 402, 403; 402, 404; 403, identifier:fields; 404, integer:5; 405, elif_clause; 405, 406; 405, 411; 406, comparison_operator:==; 406, 407; 406, 410; 407, subscript; 407, 408; 407, 409; 408, identifier:fields; 409, integer:0; 410, string:'q'; 411, block; 411, 412; 411, 421; 411, 422; 412, assert_statement; 412, 413; 412, 420; 413, comparison_operator:==; 413, 414; 413, 417; 414, subscript; 414, 415; 414, 416; 415, identifier:fields; 416, integer:1; 417, attribute; 417, 418; 417, 419; 418, identifier:last_component; 419, identifier:src; 420, string:"'q' row does not follow matching 's' row"; 421, comment; 422, expression_statement; 422, 423; 423, assignment; 423, 424; 423, 427; 424, attribute; 424, 425; 424, 426; 425, identifier:last_component; 426, identifier:quality; 427, subscript; 427, 428; 427, 429; 428, identifier:fields; 429, integer:2; 430, return_statement; 430, 431; 431, identifier:alignment
def read_next_maf( file, species_to_lengths=None, parse_e_rows=False ): """ Read the next MAF block from `file` and return as an `Alignment` instance. If `parse_i_rows` is true, empty components will be created when e rows are encountered. """ alignment = Alignment(species_to_lengths=species_to_lengths) # Attributes line line = readline( file, skip_blank=True ) if not line: return None fields = line.split() if fields[0] != 'a': raise Exception("Expected 'a ...' line") alignment.attributes = parse_attributes( fields[1:] ) if 'score' in alignment.attributes: alignment.score = alignment.attributes['score'] del alignment.attributes['score'] else: alignment.score = 0 # Sequence lines last_component = None while 1: line = readline( file ) # EOF or Blank line terminates alignment components if not line or line.isspace(): break if line.isspace(): break # Parse row fields = line.split() if fields[0] == 's': # An 's' row contains sequence for a component component = Component() component.src = fields[1] component.start = int( fields[2] ) component.size = int( fields[3] ) component.strand = fields[4] component.src_size = int( fields[5] ) if len(fields) > 6: component.text = fields[6].strip() # Add to set alignment.add_component( component ) last_component = component elif fields[0] == 'e': # An 'e' row, when no bases align for a given species this tells # us something about the synteny if parse_e_rows: component = Component() component.empty = True component.src = fields[1] component.start = int( fields[2] ) component.size = int( fields[3] ) component.strand = fields[4] component.src_size = int( fields[5] ) component.text = None synteny = fields[6].strip() assert len( synteny ) == 1, \ "Synteny status in 'e' rows should be denoted with a single character code" component.synteny_empty = synteny alignment.add_component( component ) last_component = component elif fields[0] == 'i': # An 'i' row, indicates left and right synteny status for the # previous component, we hope ;) assert fields[1] == last_component.src, "'i' row does not follow matching 's' row" last_component.synteny_left = ( fields[2], int( fields[3] ) ) last_component.synteny_right = ( fields[4], int( fields[5] ) ) elif fields[0] == 'q': assert fields[1] == last_component.src, "'q' row does not follow matching 's' row" # TODO: Should convert this to an integer array? last_component.quality = fields[2] return alignment
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:parse_record; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:lines; 6, block; 6, 7; 6, 9; 6, 10; 6, 14; 6, 55; 6, 59; 6, 60; 6, 66; 6, 70; 6, 449; 6, 450; 7, expression_statement; 7, 8; 8, comment; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 13; 12, identifier:temp_lines; 13, list:[]; 14, for_statement; 14, 15; 14, 16; 14, 17; 15, identifier:line; 16, identifier:lines; 17, block; 17, 18; 17, 33; 17, 48; 18, expression_statement; 18, 19; 19, assignment; 19, 20; 19, 21; 20, identifier:fields; 21, call; 21, 22; 21, 30; 22, attribute; 22, 23; 22, 29; 23, call; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:line; 26, identifier:rstrip; 27, argument_list; 27, 28; 28, string:"\r\n"; 29, identifier:split; 30, argument_list; 30, 31; 30, 32; 31, None; 32, integer:1; 33, if_statement; 33, 34; 33, 40; 34, comparison_operator:==; 34, 35; 34, 39; 35, call; 35, 36; 35, 37; 36, identifier:len; 37, argument_list; 37, 38; 38, identifier:fields; 39, integer:1; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, call; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:fields; 45, identifier:append; 46, argument_list; 46, 47; 47, string:""; 48, expression_statement; 48, 49; 49, call; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:temp_lines; 52, identifier:append; 53, argument_list; 53, 54; 54, identifier:fields; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:lines; 58, identifier:temp_lines; 59, comment; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:motif; 63, call; 63, 64; 63, 65; 64, identifier:TransfacMotif; 65, argument_list; 66, expression_statement; 66, 67; 67, assignment; 67, 68; 67, 69; 68, identifier:current_line; 69, integer:0; 70, while_statement; 70, 71; 70, 72; 70, 73; 71, integer:1; 72, comment; 73, block; 73, 74; 73, 83; 73, 84; 73, 92; 73, 93; 73, 105; 73, 106; 73, 114; 73, 115; 73, 139; 73, 140; 73, 183; 73, 184; 73, 242; 73, 243; 73, 304; 73, 305; 74, if_statement; 74, 75; 74, 81; 75, comparison_operator:>=; 75, 76; 75, 77; 76, identifier:current_line; 77, call; 77, 78; 77, 79; 78, identifier:len; 79, argument_list; 79, 80; 80, identifier:lines; 81, block; 81, 82; 82, break_statement; 83, comment; 84, expression_statement; 84, 85; 85, assignment; 85, 86; 85, 89; 86, pattern_list; 86, 87; 86, 88; 87, identifier:prefix; 88, identifier:rest; 89, subscript; 89, 90; 89, 91; 90, identifier:lines; 91, identifier:current_line; 92, comment; 93, if_statement; 93, 94; 93, 99; 94, comparison_operator:not; 94, 95; 94, 96; 95, identifier:prefix; 96, attribute; 96, 97; 96, 98; 97, identifier:self; 98, identifier:parse_actions; 99, block; 99, 100; 99, 104; 100, expression_statement; 100, 101; 101, augmented_assignment:+=; 101, 102; 101, 103; 102, identifier:current_line; 103, integer:1; 104, continue_statement; 105, comment; 106, expression_statement; 106, 107; 107, assignment; 107, 108; 107, 109; 108, identifier:action; 109, subscript; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:self; 112, identifier:parse_actions; 113, identifier:prefix; 114, comment; 115, if_statement; 115, 116; 115, 121; 116, comparison_operator:==; 116, 117; 116, 120; 117, subscript; 117, 118; 117, 119; 118, identifier:action; 119, integer:0; 120, string:"store_single"; 121, block; 121, 122; 121, 128; 121, 135; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 125; 124, identifier:key; 125, subscript; 125, 126; 125, 127; 126, identifier:action; 127, integer:1; 128, expression_statement; 128, 129; 129, call; 129, 130; 129, 131; 130, identifier:setattr; 131, argument_list; 131, 132; 131, 133; 131, 134; 132, identifier:motif; 133, identifier:key; 134, identifier:rest; 135, expression_statement; 135, 136; 136, augmented_assignment:+=; 136, 137; 136, 138; 137, identifier:current_line; 138, integer:1; 139, comment; 140, if_statement; 140, 141; 140, 146; 141, comparison_operator:==; 141, 142; 141, 145; 142, subscript; 142, 143; 142, 144; 143, identifier:action; 144, integer:0; 145, string:"store_single_list"; 146, block; 146, 147; 146, 153; 146, 168; 146, 179; 147, expression_statement; 147, 148; 148, assignment; 148, 149; 148, 150; 149, identifier:key; 150, subscript; 150, 151; 150, 152; 151, identifier:action; 152, integer:1; 153, if_statement; 153, 154; 153, 160; 154, not_operator; 154, 155; 155, call; 155, 156; 155, 157; 156, identifier:getattr; 157, argument_list; 157, 158; 157, 159; 158, identifier:motif; 159, identifier:key; 160, block; 160, 161; 161, expression_statement; 161, 162; 162, call; 162, 163; 162, 164; 163, identifier:setattr; 164, argument_list; 164, 165; 164, 166; 164, 167; 165, identifier:motif; 166, identifier:key; 167, list:[]; 168, expression_statement; 168, 169; 169, call; 169, 170; 169, 177; 170, attribute; 170, 171; 170, 176; 171, call; 171, 172; 171, 173; 172, identifier:getattr; 173, argument_list; 173, 174; 173, 175; 174, identifier:motif; 175, identifier:key; 176, identifier:append; 177, argument_list; 177, 178; 178, identifier:rest; 179, expression_statement; 179, 180; 180, augmented_assignment:+=; 180, 181; 180, 182; 181, identifier:current_line; 182, integer:1; 183, comment; 184, if_statement; 184, 185; 184, 190; 185, comparison_operator:==; 185, 186; 185, 189; 186, subscript; 186, 187; 186, 188; 187, identifier:action; 188, integer:0; 189, string:"store_single_key_value"; 190, block; 190, 191; 190, 197; 190, 213; 190, 228; 190, 238; 191, expression_statement; 191, 192; 192, assignment; 192, 193; 192, 194; 193, identifier:key; 194, subscript; 194, 195; 194, 196; 195, identifier:action; 196, integer:1; 197, expression_statement; 197, 198; 198, assignment; 198, 199; 198, 202; 199, pattern_list; 199, 200; 199, 201; 200, identifier:k; 201, identifier:v; 202, call; 202, 203; 202, 210; 203, attribute; 203, 204; 203, 209; 204, call; 204, 205; 204, 208; 205, attribute; 205, 206; 205, 207; 206, identifier:rest; 207, identifier:strip; 208, argument_list; 209, identifier:split; 210, argument_list; 210, 211; 210, 212; 211, string:'='; 212, integer:1; 213, if_statement; 213, 214; 213, 220; 214, not_operator; 214, 215; 215, call; 215, 216; 215, 217; 216, identifier:getattr; 217, argument_list; 217, 218; 217, 219; 218, identifier:motif; 219, identifier:key; 220, block; 220, 221; 221, expression_statement; 221, 222; 222, call; 222, 223; 222, 224; 223, identifier:setattr; 224, argument_list; 224, 225; 224, 226; 224, 227; 225, identifier:motif; 226, identifier:key; 227, dictionary; 228, expression_statement; 228, 229; 229, assignment; 229, 230; 229, 237; 230, subscript; 230, 231; 230, 236; 231, call; 231, 232; 231, 233; 232, identifier:getattr; 233, argument_list; 233, 234; 233, 235; 234, identifier:motif; 235, identifier:key; 236, identifier:k; 237, identifier:v; 238, expression_statement; 238, 239; 239, augmented_assignment:+=; 239, 240; 239, 241; 240, identifier:current_line; 241, integer:1; 242, comment; 243, if_statement; 243, 244; 243, 249; 244, comparison_operator:==; 244, 245; 244, 248; 245, subscript; 245, 246; 245, 247; 246, identifier:action; 247, integer:0; 248, string:"store_block"; 249, block; 249, 250; 249, 256; 249, 260; 249, 291; 250, expression_statement; 250, 251; 251, assignment; 251, 252; 251, 253; 252, identifier:key; 253, subscript; 253, 254; 253, 255; 254, identifier:action; 255, integer:1; 256, expression_statement; 256, 257; 257, assignment; 257, 258; 257, 259; 258, identifier:value; 259, list:[]; 260, while_statement; 260, 261; 260, 275; 261, boolean_operator:and; 261, 262; 261, 268; 262, comparison_operator:<; 262, 263; 262, 264; 263, identifier:current_line; 264, call; 264, 265; 264, 266; 265, identifier:len; 266, argument_list; 266, 267; 267, identifier:lines; 268, comparison_operator:==; 268, 269; 268, 274; 269, subscript; 269, 270; 269, 273; 270, subscript; 270, 271; 270, 272; 271, identifier:lines; 272, identifier:current_line; 273, integer:0; 274, identifier:prefix; 275, block; 275, 276; 275, 287; 276, expression_statement; 276, 277; 277, call; 277, 278; 277, 281; 278, attribute; 278, 279; 278, 280; 279, identifier:value; 280, identifier:append; 281, argument_list; 281, 282; 282, subscript; 282, 283; 282, 286; 283, subscript; 283, 284; 283, 285; 284, identifier:lines; 285, identifier:current_line; 286, integer:1; 287, expression_statement; 287, 288; 288, augmented_assignment:+=; 288, 289; 288, 290; 289, identifier:current_line; 290, integer:1; 291, expression_statement; 291, 292; 292, call; 292, 293; 292, 294; 293, identifier:setattr; 294, argument_list; 294, 295; 294, 296; 294, 297; 295, identifier:motif; 296, identifier:key; 297, call; 297, 298; 297, 301; 298, attribute; 298, 299; 298, 300; 299, identifier:str; 300, identifier:join; 301, argument_list; 301, 302; 301, 303; 302, string:"\n"; 303, identifier:value; 304, comment; 305, if_statement; 305, 306; 305, 311; 305, 312; 306, comparison_operator:==; 306, 307; 306, 310; 307, subscript; 307, 308; 307, 309; 308, identifier:action; 309, integer:0; 310, string:"store_matrix"; 311, comment; 312, block; 312, 313; 312, 321; 312, 328; 312, 332; 312, 336; 312, 340; 312, 341; 312, 413; 312, 414; 312, 415; 312, 430; 312, 440; 313, expression_statement; 313, 314; 314, assignment; 314, 315; 314, 316; 315, identifier:alphabet; 316, call; 316, 317; 316, 320; 317, attribute; 317, 318; 317, 319; 318, identifier:rest; 319, identifier:split; 320, argument_list; 321, expression_statement; 321, 322; 322, assignment; 322, 323; 322, 324; 323, identifier:alphabet_size; 324, call; 324, 325; 324, 326; 325, identifier:len; 326, argument_list; 326, 327; 327, identifier:alphabet; 328, expression_statement; 328, 329; 329, assignment; 329, 330; 329, 331; 330, identifier:rows; 331, list:[]; 332, expression_statement; 332, 333; 333, assignment; 333, 334; 333, 335; 334, identifier:pattern; 335, string:""; 336, expression_statement; 336, 337; 337, augmented_assignment:+=; 337, 338; 337, 339; 338, identifier:current_line; 339, integer:1; 340, comment; 341, while_statement; 341, 342; 341, 348; 342, comparison_operator:<; 342, 343; 342, 344; 343, identifier:current_line; 344, call; 344, 345; 344, 346; 345, identifier:len; 346, argument_list; 346, 347; 347, identifier:lines; 348, block; 348, 349; 348, 357; 348, 358; 348, 367; 348, 368; 348, 376; 348, 394; 348, 395; 348, 409; 349, expression_statement; 349, 350; 350, assignment; 350, 351; 350, 354; 351, pattern_list; 351, 352; 351, 353; 352, identifier:prefix; 353, identifier:rest; 354, subscript; 354, 355; 354, 356; 355, identifier:lines; 356, identifier:current_line; 357, comment; 358, if_statement; 358, 359; 358, 365; 359, not_operator; 359, 360; 360, call; 360, 361; 360, 364; 361, attribute; 361, 362; 361, 363; 362, identifier:prefix; 363, identifier:isdigit; 364, argument_list; 365, block; 365, 366; 366, break_statement; 367, comment; 368, expression_statement; 368, 369; 369, assignment; 369, 370; 369, 371; 370, identifier:values; 371, call; 371, 372; 371, 375; 372, attribute; 372, 373; 372, 374; 373, identifier:rest; 374, identifier:split; 375, argument_list; 376, expression_statement; 376, 377; 377, call; 377, 378; 377, 381; 378, attribute; 378, 379; 378, 380; 379, identifier:rows; 380, identifier:append; 381, argument_list; 381, 382; 382, list_comprehension; 382, 383; 382, 387; 383, call; 383, 384; 383, 385; 384, identifier:float; 385, argument_list; 385, 386; 386, identifier:_; 387, for_in_clause; 387, 388; 387, 389; 388, identifier:_; 389, subscript; 389, 390; 389, 391; 390, identifier:values; 391, slice; 391, 392; 391, 393; 392, colon; 393, identifier:alphabet_size; 394, comment; 395, if_statement; 395, 396; 395, 402; 396, comparison_operator:>; 396, 397; 396, 401; 397, call; 397, 398; 397, 399; 398, identifier:len; 399, argument_list; 399, 400; 400, identifier:values; 401, identifier:alphabet_size; 402, block; 402, 403; 403, expression_statement; 403, 404; 404, augmented_assignment:+=; 404, 405; 404, 406; 405, identifier:pattern; 406, subscript; 406, 407; 406, 408; 407, identifier:values; 408, identifier:alphabet_size; 409, expression_statement; 409, 410; 410, augmented_assignment:+=; 410, 411; 410, 412; 411, identifier:current_line; 412, integer:1; 413, comment; 414, comment; 415, if_statement; 415, 416; 415, 425; 416, comparison_operator:!=; 416, 417; 416, 421; 417, call; 417, 418; 417, 419; 418, identifier:len; 419, argument_list; 419, 420; 420, identifier:pattern; 421, call; 421, 422; 421, 423; 422, identifier:len; 423, argument_list; 423, 424; 424, identifier:rows; 425, block; 425, 426; 426, expression_statement; 426, 427; 427, assignment; 427, 428; 427, 429; 428, identifier:pattern; 429, None; 430, expression_statement; 430, 431; 431, assignment; 431, 432; 431, 433; 432, identifier:matrix; 433, call; 433, 434; 433, 437; 434, attribute; 434, 435; 434, 436; 435, identifier:FrequencyMatrix; 436, identifier:from_rows; 437, argument_list; 437, 438; 437, 439; 438, identifier:alphabet; 439, identifier:rows; 440, expression_statement; 440, 441; 441, call; 441, 442; 441, 443; 442, identifier:setattr; 443, argument_list; 443, 444; 443, 445; 443, 448; 444, identifier:motif; 445, subscript; 445, 446; 445, 447; 446, identifier:action; 447, integer:1; 448, identifier:matrix; 449, comment; 450, if_statement; 450, 451; 450, 462; 451, boolean_operator:or; 451, 452; 451, 459; 452, boolean_operator:or; 452, 453; 452, 456; 453, attribute; 453, 454; 453, 455; 454, identifier:motif; 455, identifier:id; 456, attribute; 456, 457; 456, 458; 457, identifier:motif; 458, identifier:accession; 459, attribute; 459, 460; 459, 461; 460, identifier:motif; 461, identifier:name; 462, block; 462, 463; 463, return_statement; 463, 464; 464, identifier:motif
def parse_record( self, lines ): """ Parse a TRANSFAC record out of `lines` and return a motif. """ # Break lines up temp_lines = [] for line in lines: fields = line.rstrip( "\r\n" ).split( None, 1 ) if len( fields ) == 1: fields.append( "" ) temp_lines.append( fields ) lines = temp_lines # Fill in motif from lines motif = TransfacMotif() current_line = 0 while 1: # Done parsing if no more lines to consume if current_line >= len( lines ): break # Remove prefix and first separator from line prefix, rest = lines[ current_line ] # No action for this prefix, just ignore the line if prefix not in self.parse_actions: current_line += 1 continue # Get action for line action = self.parse_actions[ prefix ] # Store a single line value if action[0] == "store_single": key = action[1] setattr( motif, key, rest ) current_line += 1 # Add a single line value to a list if action[0] == "store_single_list": key = action[1] if not getattr( motif, key ): setattr( motif, key, [] ) getattr( motif, key ).append( rest ) current_line += 1 # Add a single line value to a dictionary if action[0] == "store_single_key_value": key = action[1] k, v = rest.strip().split( '=', 1 ) if not getattr( motif, key ): setattr( motif, key, {} ) getattr( motif, key )[k] = v current_line += 1 # Store a block of text if action[0] == "store_block": key = action[1] value = [] while current_line < len( lines ) and lines[ current_line ][0] == prefix: value.append( lines[current_line][1] ) current_line += 1 setattr( motif, key, str.join( "\n", value ) ) # Store a matrix if action[0] == "store_matrix": # First line is alphabet alphabet = rest.split() alphabet_size = len( alphabet ) rows = [] pattern = "" current_line += 1 # Next lines are the rows of the matrix (we allow 0 rows) while current_line < len( lines ): prefix, rest = lines[ current_line ] # Prefix should be a two digit 0 padded row number if not prefix.isdigit(): break # The first `alphabet_size` fields are the row values values = rest.split() rows.append( [ float(_) for _ in values[:alphabet_size] ] ) # TRANSFAC includes an extra column with the IUPAC code if len( values ) > alphabet_size: pattern += values[alphabet_size] current_line += 1 # Only store the pattern if it is the correct length (meaning # that every row had an extra field) if len( pattern ) != len( rows ): pattern = None matrix = FrequencyMatrix.from_rows( alphabet, rows ) setattr( motif, action[1], matrix ) # Only return a motif if we saw at least ID or AC or NA if motif.id or motif.accession or motif.name: return motif
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:tile_interval; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 4, identifier:sources; 5, identifier:index; 6, identifier:ref_src; 7, identifier:start; 8, identifier:end; 9, default_parameter; 9, 10; 9, 11; 10, identifier:seq_db; 11, None; 12, block; 12, 13; 12, 15; 12, 16; 12, 57; 12, 63; 12, 74; 12, 75; 12, 89; 12, 97; 12, 101; 12, 167; 12, 171; 12, 188; 12, 380; 13, expression_statement; 13, 14; 14, comment; 15, comment; 16, assert_statement; 16, 17; 16, 36; 17, comparison_operator:==; 17, 18; 17, 28; 18, subscript; 18, 19; 18, 27; 19, call; 19, 20; 19, 25; 20, attribute; 20, 21; 20, 24; 21, subscript; 21, 22; 21, 23; 22, identifier:sources; 23, integer:0; 24, identifier:split; 25, argument_list; 25, 26; 26, string:'.'; 27, integer:0; 28, subscript; 28, 29; 28, 35; 29, call; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:ref_src; 32, identifier:split; 33, argument_list; 33, 34; 34, string:'.'; 35, integer:0; 36, binary_operator:%; 36, 37; 36, 38; 37, string:"%s != %s"; 38, tuple; 38, 39; 38, 49; 39, subscript; 39, 40; 39, 48; 40, call; 40, 41; 40, 46; 41, attribute; 41, 42; 41, 45; 42, subscript; 42, 43; 42, 44; 43, identifier:sources; 44, integer:0; 45, identifier:split; 46, argument_list; 46, 47; 47, string:'.'; 48, integer:0; 49, subscript; 49, 50; 49, 56; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:ref_src; 53, identifier:split; 54, argument_list; 54, 55; 55, string:'.'; 56, integer:0; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:base_len; 60, binary_operator:-; 60, 61; 60, 62; 61, identifier:end; 62, identifier:start; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:blocks; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, identifier:index; 69, identifier:get; 70, argument_list; 70, 71; 70, 72; 70, 73; 71, identifier:ref_src; 72, identifier:start; 73, identifier:end; 74, comment; 75, expression_statement; 75, 76; 76, call; 76, 77; 76, 80; 77, attribute; 77, 78; 77, 79; 78, identifier:blocks; 79, identifier:sort; 80, argument_list; 80, 81; 81, keyword_argument; 81, 82; 81, 83; 82, identifier:key; 83, lambda; 83, 84; 83, 86; 84, lambda_parameters; 84, 85; 85, identifier:t; 86, attribute; 86, 87; 86, 88; 87, identifier:t; 88, identifier:score; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:mask; 92, binary_operator:*; 92, 93; 92, 96; 93, list:[ -1 ]; 93, 94; 94, unary_operator:-; 94, 95; 95, integer:1; 96, identifier:base_len; 97, expression_statement; 97, 98; 98, assignment; 98, 99; 98, 100; 99, identifier:ref_src_size; 100, None; 101, for_statement; 101, 102; 101, 105; 101, 109; 102, pattern_list; 102, 103; 102, 104; 103, identifier:i; 104, identifier:block; 105, call; 105, 106; 105, 107; 106, identifier:enumerate; 107, argument_list; 107, 108; 108, identifier:blocks; 109, block; 109, 110; 109, 119; 109, 125; 109, 131; 109, 141; 109, 151; 110, expression_statement; 110, 111; 111, assignment; 111, 112; 111, 113; 112, identifier:ref; 113, call; 113, 114; 113, 117; 114, attribute; 114, 115; 114, 116; 115, identifier:block; 116, identifier:get_component_by_src_start; 117, argument_list; 117, 118; 118, identifier:ref_src; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:ref_src_size; 122, attribute; 122, 123; 122, 124; 123, identifier:ref; 124, identifier:src_size; 125, assert_statement; 125, 126; 126, comparison_operator:==; 126, 127; 126, 130; 127, attribute; 127, 128; 127, 129; 128, identifier:ref; 129, identifier:strand; 130, string:"+"; 131, expression_statement; 131, 132; 132, assignment; 132, 133; 132, 134; 133, identifier:slice_start; 134, call; 134, 135; 134, 136; 135, identifier:max; 136, argument_list; 136, 137; 136, 138; 137, identifier:start; 138, attribute; 138, 139; 138, 140; 139, identifier:ref; 140, identifier:start; 141, expression_statement; 141, 142; 142, assignment; 142, 143; 142, 144; 143, identifier:slice_end; 144, call; 144, 145; 144, 146; 145, identifier:min; 146, argument_list; 146, 147; 146, 148; 147, identifier:end; 148, attribute; 148, 149; 148, 150; 149, identifier:ref; 150, identifier:end; 151, for_statement; 151, 152; 151, 153; 151, 158; 152, identifier:j; 153, call; 153, 154; 153, 155; 154, identifier:range; 155, argument_list; 155, 156; 155, 157; 156, identifier:slice_start; 157, identifier:slice_end; 158, block; 158, 159; 159, expression_statement; 159, 160; 160, assignment; 160, 161; 160, 166; 161, subscript; 161, 162; 161, 163; 162, identifier:mask; 163, binary_operator:-; 163, 164; 163, 165; 164, identifier:j; 165, identifier:start; 166, identifier:i; 167, expression_statement; 167, 168; 168, assignment; 168, 169; 168, 170; 169, identifier:tiled; 170, list:[]; 171, for_statement; 171, 172; 171, 173; 171, 180; 172, identifier:i; 173, call; 173, 174; 173, 175; 174, identifier:range; 175, argument_list; 175, 176; 176, call; 176, 177; 176, 178; 177, identifier:len; 178, argument_list; 178, 179; 179, identifier:sources; 180, block; 180, 181; 181, expression_statement; 181, 182; 182, call; 182, 183; 182, 186; 183, attribute; 183, 184; 183, 185; 184, identifier:tiled; 185, identifier:append; 186, argument_list; 186, 187; 187, list:[]; 188, for_statement; 188, 189; 188, 193; 188, 197; 188, 198; 189, pattern_list; 189, 190; 189, 191; 189, 192; 190, identifier:ss; 191, identifier:ee; 192, identifier:index; 193, call; 193, 194; 193, 195; 194, identifier:intervals_from_mask; 195, argument_list; 195, 196; 196, identifier:mask; 197, comment; 198, block; 198, 199; 199, if_statement; 199, 200; 199, 203; 199, 204; 199, 278; 200, comparison_operator:<; 200, 201; 200, 202; 201, identifier:index; 202, integer:0; 203, comment; 204, block; 204, 205; 204, 257; 204, 258; 205, if_statement; 205, 206; 205, 207; 205, 241; 206, identifier:seq_db; 207, block; 207, 208; 208, expression_statement; 208, 209; 209, call; 209, 210; 209, 215; 210, attribute; 210, 211; 210, 214; 211, subscript; 211, 212; 211, 213; 212, identifier:tiled; 213, integer:0; 214, identifier:append; 215, argument_list; 215, 216; 216, call; 216, 217; 216, 234; 217, attribute; 217, 218; 217, 233; 218, call; 218, 219; 218, 226; 219, attribute; 219, 220; 219, 225; 220, attribute; 220, 221; 220, 224; 221, attribute; 221, 222; 221, 223; 222, identifier:bx; 223, identifier:seq; 224, identifier:nib; 225, identifier:NibFile; 226, argument_list; 226, 227; 227, call; 227, 228; 227, 229; 228, identifier:open; 229, argument_list; 229, 230; 230, subscript; 230, 231; 230, 232; 231, identifier:seq_db; 232, identifier:ref_src; 233, identifier:get; 234, argument_list; 234, 235; 234, 238; 235, binary_operator:+; 235, 236; 235, 237; 236, identifier:start; 237, identifier:ss; 238, binary_operator:-; 238, 239; 238, 240; 239, identifier:ee; 240, identifier:ss; 241, else_clause; 241, 242; 242, block; 242, 243; 243, expression_statement; 243, 244; 244, call; 244, 245; 244, 250; 245, attribute; 245, 246; 245, 249; 246, subscript; 246, 247; 246, 248; 247, identifier:tiled; 248, integer:0; 249, identifier:append; 250, argument_list; 250, 251; 251, binary_operator:*; 251, 252; 251, 253; 252, string:"N"; 253, parenthesized_expression; 253, 254; 254, binary_operator:-; 254, 255; 254, 256; 255, identifier:ee; 256, identifier:ss; 257, comment; 258, for_statement; 258, 259; 258, 260; 258, 265; 259, identifier:row; 260, subscript; 260, 261; 260, 262; 261, identifier:tiled; 262, slice; 262, 263; 262, 264; 263, integer:1; 264, colon; 265, block; 265, 266; 266, expression_statement; 266, 267; 267, call; 267, 268; 267, 271; 268, attribute; 268, 269; 268, 270; 269, identifier:row; 270, identifier:append; 271, argument_list; 271, 272; 272, binary_operator:*; 272, 273; 272, 274; 273, string:"-"; 274, parenthesized_expression; 274, 275; 275, binary_operator:-; 275, 276; 275, 277; 276, identifier:ee; 277, identifier:ss; 278, else_clause; 278, 279; 279, block; 279, 280; 279, 286; 279, 292; 279, 298; 279, 307; 279, 318; 279, 327; 279, 333; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 283; 282, identifier:slice_start; 283, binary_operator:+; 283, 284; 283, 285; 284, identifier:start; 285, identifier:ss; 286, expression_statement; 286, 287; 287, assignment; 287, 288; 287, 289; 288, identifier:slice_end; 289, binary_operator:+; 289, 290; 289, 291; 290, identifier:start; 291, identifier:ee; 292, expression_statement; 292, 293; 293, assignment; 293, 294; 293, 295; 294, identifier:block; 295, subscript; 295, 296; 295, 297; 296, identifier:blocks; 297, identifier:index; 298, expression_statement; 298, 299; 299, assignment; 299, 300; 299, 301; 300, identifier:ref; 301, call; 301, 302; 301, 305; 302, attribute; 302, 303; 302, 304; 303, identifier:block; 304, identifier:get_component_by_src_start; 305, argument_list; 305, 306; 306, identifier:ref_src; 307, expression_statement; 307, 308; 308, assignment; 308, 309; 308, 310; 309, identifier:sliced; 310, call; 310, 311; 310, 314; 311, attribute; 311, 312; 311, 313; 312, identifier:block; 313, identifier:slice_by_component; 314, argument_list; 314, 315; 314, 316; 314, 317; 315, identifier:ref; 316, identifier:slice_start; 317, identifier:slice_end; 318, expression_statement; 318, 319; 319, assignment; 319, 320; 319, 321; 320, identifier:sliced; 321, call; 321, 322; 321, 325; 322, attribute; 322, 323; 322, 324; 323, identifier:sliced; 324, identifier:limit_to_species; 325, argument_list; 325, 326; 326, identifier:sources; 327, expression_statement; 327, 328; 328, call; 328, 329; 328, 332; 329, attribute; 329, 330; 329, 331; 330, identifier:sliced; 331, identifier:remove_all_gap_columns; 332, argument_list; 333, for_statement; 333, 334; 333, 337; 333, 341; 334, pattern_list; 334, 335; 334, 336; 335, identifier:i; 336, identifier:src; 337, call; 337, 338; 337, 339; 338, identifier:enumerate; 339, argument_list; 339, 340; 340, identifier:sources; 341, block; 341, 342; 341, 351; 342, expression_statement; 342, 343; 343, assignment; 343, 344; 343, 345; 344, identifier:comp; 345, call; 345, 346; 345, 349; 346, attribute; 346, 347; 346, 348; 347, identifier:sliced; 348, identifier:get_component_by_src_start; 349, argument_list; 349, 350; 350, identifier:src; 351, if_statement; 351, 352; 351, 353; 351, 365; 352, identifier:comp; 353, block; 353, 354; 354, expression_statement; 354, 355; 355, call; 355, 356; 355, 361; 356, attribute; 356, 357; 356, 360; 357, subscript; 357, 358; 357, 359; 358, identifier:tiled; 359, identifier:i; 360, identifier:append; 361, argument_list; 361, 362; 362, attribute; 362, 363; 362, 364; 363, identifier:comp; 364, identifier:text; 365, else_clause; 365, 366; 366, block; 366, 367; 367, expression_statement; 367, 368; 368, call; 368, 369; 368, 374; 369, attribute; 369, 370; 369, 373; 370, subscript; 370, 371; 370, 372; 371, identifier:tiled; 372, identifier:i; 373, identifier:append; 374, argument_list; 374, 375; 375, binary_operator:*; 375, 376; 375, 377; 376, string:"-"; 377, attribute; 377, 378; 377, 379; 378, identifier:sliced; 379, identifier:text_size; 380, return_statement; 380, 381; 381, list_comprehension; 381, 382; 381, 388; 382, call; 382, 383; 382, 386; 383, attribute; 383, 384; 383, 385; 384, string:""; 385, identifier:join; 386, argument_list; 386, 387; 387, identifier:t; 388, for_in_clause; 388, 389; 388, 390; 389, identifier:t; 390, identifier:tiled
def tile_interval( sources, index, ref_src, start, end, seq_db=None ): """ Tile maf blocks onto an interval. The resulting block will span the interval exactly and contain the column from the highest scoring alignment at each position. `sources`: list of sequence source names to include in final block `index`: an instnace that can return maf blocks overlapping intervals `ref_src`: source name of the interval (ie, hg17.chr7) `start`: start of interval `end`: end of interval `seq_db`: a mapping for source names in the reference species to nib files """ # First entry in sources should also be on the reference species assert sources[0].split('.')[0] == ref_src.split('.')[0], \ "%s != %s" % ( sources[0].split('.')[0], ref_src.split('.')[0] ) base_len = end - start blocks = index.get( ref_src, start, end ) # From low to high score blocks.sort(key=lambda t: t.score) mask = [ -1 ] * base_len ref_src_size = None for i, block in enumerate( blocks ): ref = block.get_component_by_src_start( ref_src ) ref_src_size = ref.src_size assert ref.strand == "+" slice_start = max( start, ref.start ) slice_end = min( end, ref.end ) for j in range( slice_start, slice_end ): mask[j-start] = i tiled = [] for i in range( len( sources ) ): tiled.append( [] ) for ss, ee, index in intervals_from_mask( mask ): # Interval with no covering alignments if index < 0: # Get sequence if available, otherwise just use 'N' if seq_db: tiled[0].append( bx.seq.nib.NibFile( open( seq_db[ ref_src ] ) ).get( start+ss, ee-ss ) ) else: tiled[0].append( "N" * (ee-ss) ) # Gaps in all other species for row in tiled[1:]: row.append( "-" * ( ee - ss ) ) else: slice_start = start + ss slice_end = start + ee block = blocks[index] ref = block.get_component_by_src_start( ref_src ) sliced = block.slice_by_component( ref, slice_start, slice_end ) sliced = sliced.limit_to_species( sources ) sliced.remove_all_gap_columns() for i, src in enumerate( sources ): comp = sliced.get_component_by_src_start( src ) if comp: tiled[i].append( comp.text ) else: tiled[i].append( "-" * sliced.text_size ) return [ "".join( t ) for t in tiled ]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 23; 2, function_name:binned_bitsets_proximity; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 3, 20; 4, identifier:f; 5, default_parameter; 5, 6; 5, 7; 6, identifier:chrom_col; 7, integer:0; 8, default_parameter; 8, 9; 8, 10; 9, identifier:start_col; 10, integer:1; 11, default_parameter; 11, 12; 11, 13; 12, identifier:end_col; 13, integer:2; 14, default_parameter; 14, 15; 14, 16; 15, identifier:strand_col; 16, integer:5; 17, default_parameter; 17, 18; 17, 19; 18, identifier:upstream; 19, integer:0; 20, default_parameter; 20, 21; 20, 22; 21, identifier:downstream; 22, integer:0; 23, block; 23, 24; 23, 26; 23, 30; 23, 34; 23, 40; 23, 220; 24, expression_statement; 24, 25; 25, comment; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:last_chrom; 29, None; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:last_bitset; 33, None; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:bitsets; 37, call; 37, 38; 37, 39; 38, identifier:dict; 39, argument_list; 40, for_statement; 40, 41; 40, 42; 40, 43; 41, identifier:line; 42, identifier:f; 43, block; 43, 44; 43, 53; 43, 54; 43, 62; 43, 66; 43, 87; 43, 93; 43, 122; 43, 140; 43, 171; 43, 202; 43, 203; 44, if_statement; 44, 45; 44, 51; 45, call; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:line; 48, identifier:startswith; 49, argument_list; 49, 50; 50, string:"#"; 51, block; 51, 52; 52, continue_statement; 53, comment; 54, expression_statement; 54, 55; 55, assignment; 55, 56; 55, 57; 56, identifier:fields; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:line; 60, identifier:split; 61, argument_list; 62, expression_statement; 62, 63; 63, assignment; 63, 64; 63, 65; 64, identifier:strand; 65, string:"+"; 66, if_statement; 66, 67; 66, 75; 67, comparison_operator:>=; 67, 68; 67, 72; 68, call; 68, 69; 68, 70; 69, identifier:len; 70, argument_list; 70, 71; 71, identifier:fields; 72, binary_operator:+; 72, 73; 72, 74; 73, identifier:strand_col; 74, integer:1; 75, block; 75, 76; 76, if_statement; 76, 77; 76, 82; 77, comparison_operator:==; 77, 78; 77, 81; 78, subscript; 78, 79; 78, 80; 79, identifier:fields; 80, identifier:strand_col; 81, string:"-"; 82, block; 82, 83; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:strand; 86, string:"-"; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:chrom; 90, subscript; 90, 91; 90, 92; 91, identifier:fields; 92, identifier:chrom_col; 93, if_statement; 93, 94; 93, 97; 94, comparison_operator:!=; 94, 95; 94, 96; 95, identifier:chrom; 96, identifier:last_chrom; 97, block; 97, 98; 97, 112; 97, 116; 98, if_statement; 98, 99; 98, 102; 99, comparison_operator:not; 99, 100; 99, 101; 100, identifier:chrom; 101, identifier:bitsets; 102, block; 102, 103; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 108; 105, subscript; 105, 106; 105, 107; 106, identifier:bitsets; 107, identifier:chrom; 108, call; 108, 109; 108, 110; 109, identifier:BinnedBitSet; 110, argument_list; 110, 111; 111, identifier:MAX; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:last_chrom; 115, identifier:chrom; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:last_bitset; 119, subscript; 119, 120; 119, 121; 120, identifier:bitsets; 121, identifier:chrom; 122, expression_statement; 122, 123; 123, assignment; 123, 124; 123, 127; 124, pattern_list; 124, 125; 124, 126; 125, identifier:start; 126, identifier:end; 127, expression_list; 127, 128; 127, 134; 128, call; 128, 129; 128, 130; 129, identifier:int; 130, argument_list; 130, 131; 131, subscript; 131, 132; 131, 133; 132, identifier:fields; 133, identifier:start_col; 134, call; 134, 135; 134, 136; 135, identifier:int; 136, argument_list; 136, 137; 137, subscript; 137, 138; 137, 139; 138, identifier:fields; 139, identifier:end_col; 140, if_statement; 140, 141; 140, 144; 141, comparison_operator:==; 141, 142; 141, 143; 142, identifier:strand; 143, string:"+"; 144, block; 144, 145; 144, 158; 145, if_statement; 145, 146; 145, 147; 146, identifier:upstream; 147, block; 147, 148; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:start; 151, call; 151, 152; 151, 153; 152, identifier:max; 153, argument_list; 153, 154; 153, 155; 154, integer:0; 155, binary_operator:-; 155, 156; 155, 157; 156, identifier:start; 157, identifier:upstream; 158, if_statement; 158, 159; 158, 160; 159, identifier:downstream; 160, block; 160, 161; 161, expression_statement; 161, 162; 162, assignment; 162, 163; 162, 164; 163, identifier:end; 164, call; 164, 165; 164, 166; 165, identifier:min; 166, argument_list; 166, 167; 166, 168; 167, identifier:MAX; 168, binary_operator:+; 168, 169; 168, 170; 169, identifier:end; 170, identifier:downstream; 171, if_statement; 171, 172; 171, 175; 172, comparison_operator:==; 172, 173; 172, 174; 173, identifier:strand; 174, string:"-"; 175, block; 175, 176; 175, 189; 176, if_statement; 176, 177; 176, 178; 177, identifier:upstream; 178, block; 178, 179; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:end; 182, call; 182, 183; 182, 184; 183, identifier:min; 184, argument_list; 184, 185; 184, 186; 185, identifier:MAX; 186, binary_operator:+; 186, 187; 186, 188; 187, identifier:end; 188, identifier:upstream; 189, if_statement; 189, 190; 189, 191; 190, identifier:downstream; 191, block; 191, 192; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 195; 194, identifier:start; 195, call; 195, 196; 195, 197; 196, identifier:max; 197, argument_list; 197, 198; 197, 199; 198, integer:0; 199, binary_operator:-; 199, 200; 199, 201; 200, identifier:start; 201, identifier:downstream; 202, comment; 203, if_statement; 203, 204; 203, 209; 204, comparison_operator:>; 204, 205; 204, 208; 205, binary_operator:-; 205, 206; 205, 207; 206, identifier:end; 207, identifier:start; 208, integer:0; 209, block; 209, 210; 210, expression_statement; 210, 211; 211, call; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, identifier:last_bitset; 214, identifier:set_range; 215, argument_list; 215, 216; 215, 217; 216, identifier:start; 217, binary_operator:-; 217, 218; 217, 219; 218, identifier:end; 219, identifier:start; 220, return_statement; 220, 221; 221, identifier:bitsets
def binned_bitsets_proximity( f, chrom_col=0, start_col=1, end_col=2, strand_col=5, upstream=0, downstream=0 ): """Read a file into a dictionary of bitsets""" last_chrom = None last_bitset = None bitsets = dict() for line in f: if line.startswith("#"): continue # print "input=%s" % ( line ), fields = line.split() strand = "+" if len(fields) >= strand_col + 1: if fields[strand_col] == "-": strand = "-" chrom = fields[chrom_col] if chrom != last_chrom: if chrom not in bitsets: bitsets[chrom] = BinnedBitSet( MAX ) last_chrom = chrom last_bitset = bitsets[chrom] start, end = int( fields[start_col] ), int( fields[end_col] ) if strand == "+": if upstream: start = max( 0, start - upstream ) if downstream: end = min( MAX, end + downstream ) if strand == "-": if upstream: end = min( MAX, end + upstream ) if downstream: start = max( 0, start - downstream ) # print "set: start=%d\tend=%d" % ( start, end ) if end-start > 0: last_bitset.set_range( start, end-start ) return bitsets
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 10; 2, function_name:to_file; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:Class; 5, identifier:dict; 6, identifier:file; 7, default_parameter; 7, 8; 7, 9; 8, identifier:is_little_endian; 9, True; 10, block; 10, 11; 10, 13; 10, 23; 10, 31; 10, 32; 10, 44; 10, 45; 10, 46; 10, 47; 10, 48; 10, 49; 10, 60; 10, 132; 10, 133; 10, 141; 10, 142; 10, 241; 10, 242; 10, 250; 10, 257; 10, 261; 10, 297; 10, 298; 11, expression_statement; 11, 12; 12, comment; 13, expression_statement; 13, 14; 14, assignment; 14, 15; 14, 16; 15, identifier:io; 16, call; 16, 17; 16, 18; 17, identifier:BinaryFileWriter; 18, argument_list; 18, 19; 18, 20; 19, identifier:file; 20, keyword_argument; 20, 21; 20, 22; 21, identifier:is_little_endian; 22, identifier:is_little_endian; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:start_offset; 26, call; 26, 27; 26, 30; 27, attribute; 27, 28; 27, 29; 28, identifier:io; 29, identifier:tell; 30, argument_list; 31, comment; 32, expression_statement; 32, 33; 33, call; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:io; 36, identifier:seek; 37, argument_list; 37, 38; 38, binary_operator:+; 38, 39; 38, 40; 39, identifier:start_offset; 40, parenthesized_expression; 40, 41; 41, binary_operator:*; 41, 42; 41, 43; 42, integer:8; 43, integer:256; 44, comment; 45, comment; 46, comment; 47, comment; 48, comment; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:subtables; 52, list_comprehension; 52, 53; 52, 54; 53, list:[]; 54, for_in_clause; 54, 55; 54, 56; 55, identifier:i; 56, call; 56, 57; 56, 58; 57, identifier:range; 58, argument_list; 58, 59; 59, integer:256; 60, for_statement; 60, 61; 60, 64; 60, 69; 61, pattern_list; 61, 62; 61, 63; 62, identifier:key; 63, identifier:value; 64, call; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:dict; 67, identifier:items; 68, argument_list; 69, block; 69, 70; 69, 78; 69, 88; 69, 98; 69, 105; 69, 112; 69, 119; 70, expression_statement; 70, 71; 71, assignment; 71, 72; 71, 73; 72, identifier:pair_offset; 73, call; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:io; 76, identifier:tell; 77, argument_list; 78, expression_statement; 78, 79; 79, call; 79, 80; 79, 83; 80, attribute; 80, 81; 80, 82; 81, identifier:io; 82, identifier:write_uint32; 83, argument_list; 83, 84; 84, call; 84, 85; 84, 86; 85, identifier:len; 86, argument_list; 86, 87; 87, identifier:key; 88, expression_statement; 88, 89; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:io; 92, identifier:write_uint32; 93, argument_list; 93, 94; 94, call; 94, 95; 94, 96; 95, identifier:len; 96, argument_list; 96, 97; 97, identifier:value; 98, expression_statement; 98, 99; 99, call; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:io; 102, identifier:write; 103, argument_list; 103, 104; 104, identifier:key; 105, expression_statement; 105, 106; 106, call; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:io; 109, identifier:write; 110, argument_list; 110, 111; 111, identifier:value; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:hash; 115, call; 115, 116; 115, 117; 116, identifier:cdbhash; 117, argument_list; 117, 118; 118, identifier:key; 119, expression_statement; 119, 120; 120, call; 120, 121; 120, 128; 121, attribute; 121, 122; 121, 127; 122, subscript; 122, 123; 122, 124; 123, identifier:subtables; 124, binary_operator:%; 124, 125; 124, 126; 125, identifier:hash; 126, integer:256; 127, identifier:append; 128, argument_list; 128, 129; 129, tuple; 129, 130; 129, 131; 130, identifier:hash; 131, identifier:pair_offset; 132, comment; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:subtable_offset; 136, call; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:io; 139, identifier:tell; 140, argument_list; 141, comment; 142, for_statement; 142, 143; 142, 144; 142, 145; 143, identifier:subtable; 144, identifier:subtables; 145, block; 145, 146; 146, if_statement; 146, 147; 146, 153; 146, 154; 146, 155; 147, comparison_operator:>; 147, 148; 147, 152; 148, call; 148, 149; 148, 150; 149, identifier:len; 150, argument_list; 150, 151; 151, identifier:subtable; 152, integer:0; 153, comment; 154, comment; 155, block; 155, 156; 155, 165; 155, 178; 155, 220; 155, 221; 156, expression_statement; 156, 157; 157, assignment; 157, 158; 157, 159; 158, identifier:ncells; 159, binary_operator:*; 159, 160; 159, 164; 160, call; 160, 161; 160, 162; 161, identifier:len; 162, argument_list; 162, 163; 163, identifier:subtable; 164, integer:2; 165, expression_statement; 165, 166; 166, assignment; 166, 167; 166, 168; 167, identifier:cells; 168, list_comprehension; 168, 169; 168, 172; 169, tuple; 169, 170; 169, 171; 170, integer:0; 171, integer:0; 172, for_in_clause; 172, 173; 172, 174; 173, identifier:i; 174, call; 174, 175; 174, 176; 175, identifier:range; 176, argument_list; 176, 177; 177, identifier:ncells; 178, for_statement; 178, 179; 178, 182; 178, 183; 179, pattern_list; 179, 180; 179, 181; 180, identifier:hash; 181, identifier:pair_offset; 182, identifier:subtable; 183, block; 183, 184; 183, 193; 183, 211; 183, 212; 184, expression_statement; 184, 185; 185, assignment; 185, 186; 185, 187; 186, identifier:index; 187, binary_operator:%; 187, 188; 187, 192; 188, parenthesized_expression; 188, 189; 189, binary_operator:>>; 189, 190; 189, 191; 190, identifier:hash; 191, integer:8; 192, identifier:ncells; 193, while_statement; 193, 194; 193, 201; 194, comparison_operator:!=; 194, 195; 194, 200; 195, subscript; 195, 196; 195, 199; 196, subscript; 196, 197; 196, 198; 197, identifier:cells; 198, identifier:index; 199, integer:1; 200, integer:0; 201, block; 201, 202; 202, expression_statement; 202, 203; 203, assignment; 203, 204; 203, 205; 204, identifier:index; 205, binary_operator:%; 205, 206; 205, 210; 206, parenthesized_expression; 206, 207; 207, binary_operator:+; 207, 208; 207, 209; 208, identifier:index; 209, integer:1; 210, identifier:ncells; 211, comment; 212, expression_statement; 212, 213; 213, assignment; 213, 214; 213, 217; 214, subscript; 214, 215; 214, 216; 215, identifier:cells; 216, identifier:index; 217, tuple; 217, 218; 217, 219; 218, identifier:hash; 219, identifier:pair_offset; 220, comment; 221, for_statement; 221, 222; 221, 225; 221, 226; 222, pattern_list; 222, 223; 222, 224; 223, identifier:hash; 224, identifier:pair_offset; 225, identifier:cells; 226, block; 226, 227; 226, 234; 227, expression_statement; 227, 228; 228, call; 228, 229; 228, 232; 229, attribute; 229, 230; 229, 231; 230, identifier:io; 231, identifier:write_uint32; 232, argument_list; 232, 233; 233, identifier:hash; 234, expression_statement; 234, 235; 235, call; 235, 236; 235, 239; 236, attribute; 236, 237; 236, 238; 237, identifier:io; 238, identifier:write_uint32; 239, argument_list; 239, 240; 240, identifier:pair_offset; 241, comment; 242, expression_statement; 242, 243; 243, assignment; 243, 244; 243, 245; 244, identifier:end_offset; 245, call; 245, 246; 245, 249; 246, attribute; 246, 247; 246, 248; 247, identifier:io; 248, identifier:tell; 249, argument_list; 250, expression_statement; 250, 251; 251, call; 251, 252; 251, 255; 252, attribute; 252, 253; 252, 254; 253, identifier:io; 254, identifier:seek; 255, argument_list; 255, 256; 256, identifier:start_offset; 257, expression_statement; 257, 258; 258, assignment; 258, 259; 258, 260; 259, identifier:index; 260, identifier:subtable_offset; 261, for_statement; 261, 262; 261, 263; 261, 264; 262, identifier:subtable; 263, identifier:subtables; 264, block; 264, 265; 264, 272; 264, 284; 264, 285; 265, expression_statement; 265, 266; 266, call; 266, 267; 266, 270; 267, attribute; 267, 268; 267, 269; 268, identifier:io; 269, identifier:write_uint32; 270, argument_list; 270, 271; 271, identifier:index; 272, expression_statement; 272, 273; 273, call; 273, 274; 273, 277; 274, attribute; 274, 275; 274, 276; 275, identifier:io; 276, identifier:write_uint32; 277, argument_list; 277, 278; 278, call; 278, 279; 278, 280; 279, identifier:len; 280, argument_list; 280, 281; 281, binary_operator:*; 281, 282; 281, 283; 282, identifier:subtable; 283, integer:2; 284, comment; 285, expression_statement; 285, 286; 286, augmented_assignment:+=; 286, 287; 286, 288; 287, identifier:index; 288, binary_operator:*; 288, 289; 288, 296; 289, parenthesized_expression; 289, 290; 290, binary_operator:*; 290, 291; 290, 295; 291, call; 291, 292; 291, 293; 292, identifier:len; 293, argument_list; 293, 294; 294, identifier:subtable; 295, integer:2; 296, integer:8; 297, comment; 298, expression_statement; 298, 299; 299, call; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, identifier:io; 302, identifier:seek; 303, argument_list; 303, 304; 304, identifier:end_offset
def to_file( Class, dict, file, is_little_endian=True ): """ For constructing a CDB structure in a file. Able to calculate size on disk and write to a file """ io = BinaryFileWriter( file, is_little_endian=is_little_endian ) start_offset = io.tell() # Header is of fixed length io.seek( start_offset + ( 8 * 256 ) ) # For each item, key and value length (written as length prefixed # strings). We also calculate the subtables on this pass. # NOTE: This requires the key and value be byte strings, support for # dealing with encoding specific value types should be # added to this wrapper subtables = [ [] for i in range(256) ] for key, value in dict.items(): pair_offset = io.tell() io.write_uint32( len( key ) ) io.write_uint32( len( value ) ) io.write( key ) io.write( value ) hash = cdbhash( key ) subtables[ hash % 256 ].append( ( hash, pair_offset ) ) # Save the offset where the subtables will start subtable_offset = io.tell() # Write subtables for subtable in subtables: if len( subtable ) > 0: # Construct hashtable to be twice the size of the number # of items in the subtable, and built it in memory ncells = len( subtable ) * 2 cells = [ (0,0) for i in range( ncells ) ] for hash, pair_offset in subtable: index = ( hash >> 8 ) % ncells while cells[index][1] != 0: index = ( index + 1 ) % ncells # Guaranteed to find a non-empty cell cells[index] = ( hash, pair_offset ) # Write subtable for hash, pair_offset in cells: io.write_uint32( hash ) io.write_uint32( pair_offset ) # Go back and write the header end_offset = io.tell() io.seek( start_offset ) index = subtable_offset for subtable in subtables: io.write_uint32( index ) io.write_uint32( len( subtable * 2 ) ) # For each cell in the subtable, a hash and a pointer to a value index += ( len( subtable ) * 2 ) * 8 # Leave fp at end of cdb io.seek( end_offset )
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:transform; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:elem; 5, identifier:chain_CT_CQ; 6, identifier:max_gap; 7, block; 7, 8; 7, 10; 7, 17; 7, 49; 7, 80; 7, 86; 7, 92; 7, 111; 7, 131; 7, 139; 7, 140; 7, 212; 7, 219; 7, 226; 7, 244; 7, 245; 7, 263; 7, 264; 7, 323; 7, 358; 8, expression_statement; 8, 9; 9, comment; 10, expression_statement; 10, 11; 11, assignment; 11, 12; 11, 16; 12, tuple_pattern; 12, 13; 12, 14; 12, 15; 13, identifier:chain; 14, identifier:CT; 15, identifier:CQ; 16, identifier:chain_CT_CQ; 17, expression_statement; 17, 18; 18, assignment; 18, 19; 18, 22; 19, pattern_list; 19, 20; 19, 21; 20, identifier:start; 21, identifier:end; 22, expression_list; 22, 23; 22, 36; 23, binary_operator:-; 23, 24; 23, 33; 24, call; 24, 25; 24, 26; 25, identifier:max; 26, argument_list; 26, 27; 26, 30; 27, subscript; 27, 28; 27, 29; 28, identifier:elem; 29, string:'start'; 30, attribute; 30, 31; 30, 32; 31, identifier:chain; 32, identifier:tStart; 33, attribute; 33, 34; 33, 35; 34, identifier:chain; 35, identifier:tStart; 36, binary_operator:-; 36, 37; 36, 46; 37, call; 37, 38; 37, 39; 38, identifier:min; 39, argument_list; 39, 40; 39, 43; 40, subscript; 40, 41; 40, 42; 41, identifier:elem; 42, string:'end'; 43, attribute; 43, 44; 43, 45; 44, identifier:chain; 45, identifier:tEnd; 46, attribute; 46, 47; 46, 48; 47, identifier:chain; 48, identifier:tStart; 49, assert_statement; 49, 50; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:np; 53, identifier:all; 54, argument_list; 54, 55; 55, comparison_operator:==; 55, 56; 55, 68; 56, parenthesized_expression; 56, 57; 57, binary_operator:-; 57, 58; 57, 63; 58, subscript; 58, 59; 58, 60; 58, 62; 59, identifier:CT; 60, slice; 60, 61; 61, colon; 62, integer:1; 63, subscript; 63, 64; 63, 65; 63, 67; 64, identifier:CT; 65, slice; 65, 66; 66, colon; 67, integer:0; 68, parenthesized_expression; 68, 69; 69, binary_operator:-; 69, 70; 69, 75; 70, subscript; 70, 71; 70, 72; 70, 74; 71, identifier:CQ; 72, slice; 72, 73; 73, colon; 74, integer:1; 75, subscript; 75, 76; 75, 77; 75, 79; 76, identifier:CQ; 77, slice; 77, 78; 78, colon; 79, integer:0; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:to_chrom; 83, attribute; 83, 84; 83, 85; 84, identifier:chain; 85, identifier:qName; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:to_gab_start; 89, attribute; 89, 90; 89, 91; 90, identifier:chain; 91, identifier:qStart; 92, expression_statement; 92, 93; 93, assignment; 93, 94; 93, 95; 94, identifier:start_idx; 95, subscript; 95, 96; 95, 110; 96, subscript; 96, 97; 96, 109; 97, call; 97, 98; 97, 101; 98, attribute; 98, 99; 98, 100; 99, identifier:np; 100, identifier:where; 101, argument_list; 101, 102; 102, comparison_operator:>; 102, 103; 102, 108; 103, subscript; 103, 104; 103, 105; 103, 107; 104, identifier:CT; 105, slice; 105, 106; 106, colon; 107, integer:1; 108, identifier:start; 109, integer:0; 110, integer:0; 111, expression_statement; 111, 112; 112, assignment; 112, 113; 112, 114; 113, identifier:end_idx; 114, subscript; 114, 115; 114, 129; 115, subscript; 115, 116; 115, 128; 116, call; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:np; 119, identifier:where; 120, argument_list; 120, 121; 121, comparison_operator:<; 121, 122; 121, 127; 122, subscript; 122, 123; 122, 124; 122, 126; 123, identifier:CT; 124, slice; 124, 125; 125, colon; 126, integer:0; 127, identifier:end; 128, integer:0; 129, unary_operator:-; 129, 130; 130, integer:1; 131, if_statement; 131, 132; 131, 135; 131, 136; 132, comparison_operator:>; 132, 133; 132, 134; 133, identifier:start_idx; 134, identifier:end_idx; 135, comment; 136, block; 136, 137; 137, return_statement; 137, 138; 138, list:[]; 139, comment; 140, if_statement; 140, 141; 140, 150; 141, boolean_operator:and; 141, 142; 141, 145; 142, comparison_operator:>=; 142, 143; 142, 144; 143, identifier:max_gap; 144, integer:0; 145, comparison_operator:<; 145, 146; 145, 147; 146, identifier:start_idx; 147, binary_operator:-; 147, 148; 147, 149; 148, identifier:end_idx; 149, integer:1; 150, block; 150, 151; 151, if_statement; 151, 152; 151, 209; 152, boolean_operator:or; 152, 153; 152, 181; 153, comparison_operator:>; 153, 154; 153, 180; 154, call; 154, 155; 154, 158; 155, attribute; 155, 156; 155, 157; 156, identifier:np; 157, identifier:max; 158, argument_list; 158, 159; 159, binary_operator:-; 159, 160; 159, 170; 160, subscript; 160, 161; 160, 162; 160, 169; 161, identifier:CT; 162, slice; 162, 163; 162, 167; 162, 168; 163, parenthesized_expression; 163, 164; 164, binary_operator:+; 164, 165; 164, 166; 165, identifier:start_idx; 166, integer:1; 167, colon; 168, identifier:end_idx; 169, integer:0; 170, subscript; 170, 171; 170, 172; 170, 179; 171, identifier:CT; 172, slice; 172, 173; 172, 174; 172, 175; 173, identifier:start_idx; 174, colon; 175, parenthesized_expression; 175, 176; 176, binary_operator:-; 176, 177; 176, 178; 177, identifier:end_idx; 178, integer:1; 179, integer:1; 180, identifier:max_gap; 181, comparison_operator:>; 181, 182; 181, 208; 182, call; 182, 183; 182, 186; 183, attribute; 183, 184; 183, 185; 184, identifier:np; 185, identifier:max; 186, argument_list; 186, 187; 187, binary_operator:-; 187, 188; 187, 198; 188, subscript; 188, 189; 188, 190; 188, 197; 189, identifier:CQ; 190, slice; 190, 191; 190, 195; 190, 196; 191, parenthesized_expression; 191, 192; 192, binary_operator:+; 192, 193; 192, 194; 193, identifier:start_idx; 194, integer:1; 195, colon; 196, identifier:end_idx; 197, integer:0; 198, subscript; 198, 199; 198, 200; 198, 207; 199, identifier:CQ; 200, slice; 200, 201; 200, 202; 200, 203; 201, identifier:start_idx; 202, colon; 203, parenthesized_expression; 203, 204; 204, binary_operator:-; 204, 205; 204, 206; 205, identifier:end_idx; 206, integer:1; 207, integer:1; 208, identifier:max_gap; 209, block; 209, 210; 210, return_statement; 210, 211; 211, list:[]; 212, assert_statement; 212, 213; 213, comparison_operator:<; 213, 214; 213, 215; 214, identifier:start; 215, subscript; 215, 216; 215, 217; 215, 218; 216, identifier:CT; 217, identifier:start_idx; 218, integer:1; 219, assert_statement; 219, 220; 220, comparison_operator:<; 220, 221; 220, 225; 221, subscript; 221, 222; 221, 223; 221, 224; 222, identifier:CT; 223, identifier:end_idx; 224, integer:0; 225, identifier:end; 226, expression_statement; 226, 227; 227, assignment; 227, 228; 227, 229; 228, identifier:to_start; 229, binary_operator:+; 229, 230; 229, 234; 230, subscript; 230, 231; 230, 232; 230, 233; 231, identifier:CQ; 232, identifier:start_idx; 233, integer:0; 234, call; 234, 235; 234, 236; 235, identifier:max; 236, argument_list; 236, 237; 236, 238; 237, integer:0; 238, binary_operator:-; 238, 239; 238, 240; 239, identifier:start; 240, subscript; 240, 241; 240, 242; 240, 243; 241, identifier:CT; 242, identifier:start_idx; 243, integer:0; 244, comment; 245, expression_statement; 245, 246; 246, assignment; 246, 247; 246, 248; 247, identifier:to_end; 248, binary_operator:-; 248, 249; 248, 253; 249, subscript; 249, 250; 249, 251; 249, 252; 250, identifier:CQ; 251, identifier:end_idx; 252, integer:1; 253, call; 253, 254; 253, 255; 254, identifier:max; 255, argument_list; 255, 256; 255, 257; 256, integer:0; 257, binary_operator:-; 257, 258; 257, 262; 258, subscript; 258, 259; 258, 260; 258, 261; 259, identifier:CT; 260, identifier:end_idx; 261, integer:1; 262, identifier:end; 263, comment; 264, if_statement; 264, 265; 264, 268; 264, 269; 264, 277; 265, comparison_operator:==; 265, 266; 265, 267; 266, identifier:start_idx; 267, identifier:end_idx; 268, comment; 269, block; 269, 270; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:slices; 273, list:[(to_start, to_end)]; 273, 274; 274, tuple; 274, 275; 274, 276; 275, identifier:to_start; 276, identifier:to_end; 277, else_clause; 277, 278; 278, block; 278, 279; 278, 289; 278, 311; 279, expression_statement; 279, 280; 280, assignment; 280, 281; 280, 282; 281, identifier:slices; 282, list:[(to_start, CQ[start_idx,1])]; 282, 283; 283, tuple; 283, 284; 283, 285; 284, identifier:to_start; 285, subscript; 285, 286; 285, 287; 285, 288; 286, identifier:CQ; 287, identifier:start_idx; 288, integer:1; 289, expression_statement; 289, 290; 290, augmented_assignment:+=; 290, 291; 290, 292; 291, identifier:slices; 292, list_comprehension; 292, 293; 292, 302; 293, tuple; 293, 294; 293, 298; 294, subscript; 294, 295; 294, 296; 294, 297; 295, identifier:CQ; 296, identifier:i; 297, integer:0; 298, subscript; 298, 299; 298, 300; 298, 301; 299, identifier:CQ; 300, identifier:i; 301, integer:1; 302, for_in_clause; 302, 303; 302, 304; 303, identifier:i; 304, call; 304, 305; 304, 306; 305, identifier:range; 306, argument_list; 306, 307; 306, 310; 307, binary_operator:+; 307, 308; 307, 309; 308, identifier:start_idx; 309, integer:1; 310, identifier:end_idx; 311, expression_statement; 311, 312; 312, call; 312, 313; 312, 316; 313, attribute; 313, 314; 313, 315; 314, identifier:slices; 315, identifier:append; 316, argument_list; 316, 317; 317, tuple; 317, 318; 317, 322; 318, subscript; 318, 319; 318, 320; 318, 321; 319, identifier:CQ; 320, identifier:end_idx; 321, integer:0; 322, identifier:to_end; 323, if_statement; 323, 324; 323, 329; 324, comparison_operator:==; 324, 325; 324, 328; 325, attribute; 325, 326; 325, 327; 326, identifier:chain; 327, identifier:qStrand; 328, string:'-'; 329, block; 329, 330; 329, 340; 330, expression_statement; 330, 331; 331, assignment; 331, 332; 331, 333; 332, identifier:Sz; 333, binary_operator:-; 333, 334; 333, 337; 334, attribute; 334, 335; 334, 336; 335, identifier:chain; 336, identifier:qEnd; 337, attribute; 337, 338; 337, 339; 338, identifier:chain; 339, identifier:qStart; 340, expression_statement; 340, 341; 341, assignment; 341, 342; 341, 343; 342, identifier:slices; 343, list_comprehension; 343, 344; 343, 355; 344, tuple; 344, 345; 344, 350; 345, binary_operator:-; 345, 346; 345, 347; 346, identifier:Sz; 347, subscript; 347, 348; 347, 349; 348, identifier:t; 349, integer:1; 350, binary_operator:-; 350, 351; 350, 352; 351, identifier:Sz; 352, subscript; 352, 353; 352, 354; 353, identifier:t; 354, integer:0; 355, for_in_clause; 355, 356; 355, 357; 356, identifier:t; 357, identifier:slices; 358, return_statement; 358, 359; 359, list_comprehension; 359, 360; 359, 375; 360, tuple; 360, 361; 360, 362; 360, 367; 360, 372; 361, identifier:to_chrom; 362, binary_operator:+; 362, 363; 362, 364; 363, identifier:to_gab_start; 364, subscript; 364, 365; 364, 366; 365, identifier:t; 366, integer:0; 367, binary_operator:+; 367, 368; 367, 369; 368, identifier:to_gab_start; 369, subscript; 369, 370; 369, 371; 370, identifier:t; 371, integer:1; 372, subscript; 372, 373; 372, 374; 373, identifier:elem; 374, string:'id'; 375, for_in_clause; 375, 376; 375, 377; 376, identifier:t; 377, identifier:slices
def transform(elem, chain_CT_CQ, max_gap): """transform the coordinates of this elem into the other species. elem intersects this chain's ginterval. :return: a list of the type [(to_chr, start, end, elem[id]) ... ]""" (chain, CT, CQ) = chain_CT_CQ start, end = max(elem['start'], chain.tStart) - chain.tStart, min(elem['end'], chain.tEnd) - chain.tStart assert np.all( (CT[:,1] - CT[:,0]) == (CQ[:,1] - CQ[:,0]) ) to_chrom = chain.qName to_gab_start = chain.qStart start_idx = np.where( CT[:,1] > start )[0][0] end_idx = np.where( CT[:,0] < end )[0][-1] if start_idx > end_idx: #maps to a gap region on the other species return [] ## apply the gap threshold if max_gap >= 0 and start_idx < end_idx - 1: if np.max(CT[(start_idx+1):end_idx,0] - CT[start_idx:(end_idx-1),1]) > max_gap or np.max(CQ[(start_idx+1):end_idx,0] - CQ[start_idx:(end_idx-1),1]) > max_gap: return [] assert start < CT[start_idx, 1] assert CT[end_idx, 0] < end to_start = CQ[start_idx, 0] + max(0, start - CT[start_idx,0]) # correct if on middle of interval to_end = CQ[end_idx, 1] - max(0, CT[end_idx, 1] - end) # idem if start_idx == end_idx: #elem falls in a single run of matches slices = [(to_start, to_end)] else: slices = [(to_start, CQ[start_idx,1])] slices += [(CQ[i,0], CQ[i,1]) for i in range(start_idx+1, end_idx)] slices.append( (CQ[end_idx,0], to_end) ) if chain.qStrand == '-': Sz = chain.qEnd - chain.qStart slices = [(Sz-t[1], Sz-t[0]) for t in slices] return [(to_chrom, to_gab_start + t[0], to_gab_start + t[1], elem['id']) for t in slices]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:visit_Method; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:method; 6, block; 6, 7; 6, 9; 6, 17; 6, 62; 6, 90; 6, 113; 6, 114; 6, 115; 6, 139; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:resolved_method; 12, attribute; 12, 13; 12, 16; 13, attribute; 13, 14; 13, 15; 14, identifier:method; 15, identifier:resolved; 16, identifier:type; 17, function_definition; 17, 18; 17, 19; 17, 22; 17, 23; 18, function_name:get_params; 19, parameters; 19, 20; 19, 21; 20, identifier:method; 21, identifier:extra_bindings; 22, comment; 23, block; 23, 24; 23, 28; 23, 60; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:result; 27, list:[]; 28, for_statement; 28, 29; 28, 30; 28, 33; 29, identifier:param; 30, attribute; 30, 31; 30, 32; 31, identifier:method; 32, identifier:params; 33, block; 33, 34; 33, 51; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:resolved_param; 37, call; 37, 38; 37, 39; 38, identifier:texpr; 39, argument_list; 39, 40; 39, 45; 39, 50; 40, attribute; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:param; 43, identifier:resolved; 44, identifier:type; 45, attribute; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:param; 48, identifier:resolved; 49, identifier:bindings; 50, identifier:extra_bindings; 51, expression_statement; 51, 52; 52, call; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:result; 55, identifier:append; 56, argument_list; 56, 57; 57, attribute; 57, 58; 57, 59; 58, identifier:resolved_param; 59, identifier:id; 60, return_statement; 60, 61; 61, identifier:result; 62, function_definition; 62, 63; 62, 64; 62, 67; 62, 68; 63, function_name:get_return_type; 64, parameters; 64, 65; 64, 66; 65, identifier:method; 66, identifier:extra_bindings; 67, comment; 68, block; 68, 69; 69, return_statement; 69, 70; 70, attribute; 70, 71; 70, 89; 71, call; 71, 72; 71, 73; 72, identifier:texpr; 73, argument_list; 73, 74; 73, 81; 73, 88; 74, attribute; 74, 75; 74, 80; 75, attribute; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:method; 78, identifier:type; 79, identifier:resolved; 80, identifier:type; 81, attribute; 81, 82; 81, 87; 82, attribute; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:method; 85, identifier:type; 86, identifier:resolved; 87, identifier:bindings; 88, identifier:extra_bindings; 89, identifier:id; 90, function_definition; 90, 91; 90, 92; 90, 96; 91, function_name:signature; 92, parameters; 92, 93; 92, 94; 92, 95; 93, identifier:method; 94, identifier:return_type; 95, identifier:params; 96, block; 96, 97; 97, return_statement; 97, 98; 98, binary_operator:%; 98, 99; 98, 100; 99, string:"%s %s(%s)"; 100, tuple; 100, 101; 100, 102; 100, 107; 101, identifier:return_type; 102, attribute; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:method; 105, identifier:name; 106, identifier:text; 107, call; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, string:", "; 110, identifier:join; 111, argument_list; 111, 112; 112, identifier:params; 113, comment; 114, comment; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:interfaces; 118, call; 118, 119; 118, 120; 119, identifier:list; 120, generator_expression; 120, 121; 120, 122; 120, 129; 121, identifier:t; 122, for_in_clause; 122, 123; 122, 124; 123, identifier:t; 124, attribute; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:method; 127, identifier:clazz; 128, identifier:bases; 129, if_clause; 129, 130; 130, call; 130, 131; 130, 132; 131, identifier:isinstance; 132, argument_list; 132, 133; 132, 138; 133, attribute; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:t; 136, identifier:resolved; 137, identifier:type; 138, identifier:Interface; 139, for_statement; 139, 140; 139, 141; 139, 142; 140, identifier:interface; 141, identifier:interfaces; 142, block; 142, 143; 142, 149; 143, expression_statement; 143, 144; 144, assignment; 144, 145; 144, 146; 145, identifier:interfaceTypeExpr; 146, attribute; 146, 147; 146, 148; 147, identifier:interface; 148, identifier:resolved; 149, for_statement; 149, 150; 149, 151; 149, 156; 150, identifier:definition; 151, attribute; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:interfaceTypeExpr; 154, identifier:type; 155, identifier:definitions; 156, block; 156, 157; 157, if_statement; 157, 158; 157, 169; 158, comparison_operator:==; 158, 159; 158, 164; 159, attribute; 159, 160; 159, 163; 160, attribute; 160, 161; 160, 162; 161, identifier:definition; 162, identifier:name; 163, identifier:text; 164, attribute; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:method; 167, identifier:name; 168, identifier:text; 169, block; 169, 170; 169, 178; 169, 192; 169, 202; 169, 216; 169, 226; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:resolved_definition; 173, attribute; 173, 174; 173, 177; 174, attribute; 174, 175; 174, 176; 175, identifier:definition; 176, identifier:resolved; 177, identifier:type; 178, expression_statement; 178, 179; 179, assignment; 179, 180; 179, 181; 180, identifier:method_params; 181, call; 181, 182; 181, 183; 182, identifier:get_params; 183, argument_list; 183, 184; 183, 185; 184, identifier:resolved_method; 185, attribute; 185, 186; 185, 191; 186, attribute; 186, 187; 186, 190; 187, attribute; 187, 188; 187, 189; 188, identifier:method; 189, identifier:clazz; 190, identifier:resolved; 191, identifier:bindings; 192, expression_statement; 192, 193; 193, assignment; 193, 194; 193, 195; 194, identifier:definition_params; 195, call; 195, 196; 195, 197; 196, identifier:get_params; 197, argument_list; 197, 198; 197, 199; 198, identifier:resolved_definition; 199, attribute; 199, 200; 199, 201; 200, identifier:interfaceTypeExpr; 201, identifier:bindings; 202, expression_statement; 202, 203; 203, assignment; 203, 204; 203, 205; 204, identifier:method_return; 205, call; 205, 206; 205, 207; 206, identifier:get_return_type; 207, argument_list; 207, 208; 207, 209; 208, identifier:resolved_method; 209, attribute; 209, 210; 209, 215; 210, attribute; 210, 211; 210, 214; 211, attribute; 211, 212; 211, 213; 212, identifier:method; 213, identifier:clazz; 214, identifier:resolved; 215, identifier:bindings; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 219; 218, identifier:definition_return; 219, call; 219, 220; 219, 221; 220, identifier:get_return_type; 221, argument_list; 221, 222; 221, 223; 222, identifier:resolved_definition; 223, attribute; 223, 224; 223, 225; 224, identifier:interfaceTypeExpr; 225, identifier:bindings; 226, if_statement; 226, 227; 226, 234; 227, boolean_operator:or; 227, 228; 227, 231; 228, comparison_operator:!=; 228, 229; 228, 230; 229, identifier:method_params; 230, identifier:definition_params; 231, comparison_operator:!=; 231, 232; 231, 233; 232, identifier:method_return; 233, identifier:definition_return; 234, block; 234, 235; 235, expression_statement; 235, 236; 236, call; 236, 237; 236, 242; 237, attribute; 237, 238; 237, 241; 238, attribute; 238, 239; 238, 240; 239, identifier:self; 240, identifier:errors; 241, identifier:append; 242, argument_list; 242, 243; 243, binary_operator:%; 243, 244; 243, 245; 244, string:"%s: method signature '%s' on %s does not match method '%s' on interface %s"; 245, tuple; 245, 246; 245, 250; 245, 256; 245, 265; 245, 271; 246, call; 246, 247; 246, 248; 247, identifier:lineinfo; 248, argument_list; 248, 249; 249, identifier:method; 250, call; 250, 251; 250, 252; 251, identifier:signature; 252, argument_list; 252, 253; 252, 254; 252, 255; 253, identifier:resolved_method; 254, identifier:method_return; 255, identifier:method_params; 256, attribute; 256, 257; 256, 264; 257, attribute; 257, 258; 257, 263; 258, attribute; 258, 259; 258, 262; 259, attribute; 259, 260; 259, 261; 260, identifier:method; 261, identifier:clazz; 262, identifier:resolved; 263, identifier:type; 264, identifier:id; 265, call; 265, 266; 265, 267; 266, identifier:signature; 267, argument_list; 267, 268; 267, 269; 267, 270; 268, identifier:resolved_definition; 269, identifier:definition_return; 270, identifier:definition_params; 271, attribute; 271, 272; 271, 277; 272, attribute; 272, 273; 272, 276; 273, attribute; 273, 274; 273, 275; 274, identifier:interface; 275, identifier:resolved; 276, identifier:type; 277, identifier:id
def visit_Method(self, method): """ Ensure method has the same signature matching method on parent interface. :param method: L{quarkc.ast.Method} instance. """ resolved_method = method.resolved.type def get_params(method, extra_bindings): # The Method should already be the resolved version. result = [] for param in method.params: resolved_param = texpr(param.resolved.type, param.resolved.bindings, extra_bindings) result.append(resolved_param.id) return result def get_return_type(method, extra_bindings): # The Method should already be the resolved version. return texpr(method.type.resolved.type, method.type.resolved.bindings, extra_bindings).id def signature(method, return_type, params): return "%s %s(%s)" % (return_type, method.name.text, ", ".join(params)) # Ensure the method has the same signature as matching methods on parent # interfaces: interfaces = list(t for t in method.clazz.bases if isinstance(t.resolved.type, Interface)) for interface in interfaces: interfaceTypeExpr = interface.resolved for definition in interfaceTypeExpr.type.definitions: if definition.name.text == method.name.text: resolved_definition = definition.resolved.type method_params = get_params(resolved_method, method.clazz.resolved.bindings) definition_params = get_params(resolved_definition, interfaceTypeExpr.bindings) method_return = get_return_type(resolved_method, method.clazz.resolved.bindings) definition_return = get_return_type(resolved_definition, interfaceTypeExpr.bindings) if method_params != definition_params or method_return != definition_return: self.errors.append( "%s: method signature '%s' on %s does not match method '%s' on interface %s" % ( lineinfo(method), signature(resolved_method, method_return, method_params), method.clazz.resolved.type.id, signature(resolved_definition, definition_return, definition_params), interface.resolved.type.id))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:file_search; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:self; 5, identifier:query; 6, default_parameter; 6, 7; 6, 8; 7, identifier:offset; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:timeout; 11, None; 12, block; 12, 13; 12, 15; 12, 32; 12, 76; 13, expression_statement; 13, 14; 14, comment; 15, expression_statement; 15, 16; 16, assignment; 16, 17; 16, 18; 17, identifier:params; 18, call; 18, 19; 18, 20; 19, identifier:dict; 20, argument_list; 20, 21; 20, 26; 20, 29; 21, keyword_argument; 21, 22; 21, 23; 22, identifier:apikey; 23, attribute; 23, 24; 23, 25; 24, identifier:self; 25, identifier:api_key; 26, keyword_argument; 26, 27; 26, 28; 27, identifier:query; 28, identifier:query; 29, keyword_argument; 29, 30; 29, 31; 30, identifier:offset; 31, identifier:offset; 32, try_statement; 32, 33; 32, 58; 33, block; 33, 34; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:response; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:requests; 40, identifier:get; 41, argument_list; 41, 42; 41, 47; 41, 50; 41, 55; 42, binary_operator:+; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:self; 45, identifier:base; 46, string:'file/search'; 47, keyword_argument; 47, 48; 47, 49; 48, identifier:params; 49, identifier:params; 50, keyword_argument; 50, 51; 50, 52; 51, identifier:proxies; 52, attribute; 52, 53; 52, 54; 53, identifier:self; 54, identifier:proxies; 55, keyword_argument; 55, 56; 55, 57; 56, identifier:timeout; 57, identifier:timeout; 58, except_clause; 58, 59; 58, 65; 59, as_pattern; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:requests; 62, identifier:RequestException; 63, as_pattern_target; 63, 64; 64, identifier:e; 65, block; 65, 66; 66, return_statement; 66, 67; 67, call; 67, 68; 67, 69; 68, identifier:dict; 69, argument_list; 69, 70; 70, keyword_argument; 70, 71; 70, 72; 71, identifier:error; 72, call; 72, 73; 72, 74; 73, identifier:str; 74, argument_list; 74, 75; 75, identifier:e; 76, return_statement; 76, 77; 77, call; 77, 78; 77, 79; 78, identifier:_return_response_and_status_code; 79, argument_list; 79, 80; 80, identifier:response
def file_search(self, query, offset=None, timeout=None): """ Search for samples. In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we call "advanced reverse searches". Reverse searches take you from a file property to a list of files that match that property. For example, this functionality enables you to retrieve all those files marked by at least one antivirus vendor as Zbot, or all those files that have a size under 90KB and are detected by at least 10 antivirus solutions, or all those PDF files that have an invalid XREF section, etc. This API is equivalent to VirusTotal Intelligence advanced searches. A very wide variety of search modifiers are available, including: file size, file type, first submission date to VirusTotal, last submission date to VirusTotal, number of positives, dynamic behavioural properties, binary content, submission file name, and a very long etcetera. The full list of search modifiers allowed for file search queries is documented at: https://www.virustotal.com/intelligence/help/file-search/#search-modifiers NOTE: Daily limited! No matter what API step you have licensed, this API call is limited to 50K requests per day. If you need any more, chances are you are approaching your engineering problem erroneously and you can probably solve it using the file distribution call. Do not hesitate to contact us with your particular use case. EXAMPLE: search_options = 'type:peexe size:90kb+ positives:5+ behaviour:"taskkill"' :param query: A search modifier compliant file search query. :param offset: (optional) The offset value returned by a previously issued identical query, allows you to paginate over the results. If not specified the first 300 matching files sorted according to last submission date to VirusTotal in a descending fashion will be returned. :param timeout: The amount of time in seconds the request should wait before timing out. :return: JSON response - By default the list returned contains at most 300 hashes, ordered according to last submission date to VirusTotal in a descending fashion. """ params = dict(apikey=self.api_key, query=query, offset=offset) try: response = requests.get(self.base + 'file/search', params=params, proxies=self.proxies, timeout=timeout) except requests.RequestException as e: return dict(error=str(e)) return _return_response_and_status_code(response)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:_handle_retry; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:resp; 6, block; 6, 7; 6, 9; 6, 20; 6, 30; 6, 50; 6, 69; 6, 119; 6, 154; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 15; 11, pattern_list; 11, 12; 11, 13; 11, 14; 12, identifier:exc_t; 13, identifier:exc_v; 14, identifier:exc_tb; 15, call; 15, 16; 15, 19; 16, attribute; 16, 17; 16, 18; 17, identifier:sys; 18, identifier:exc_info; 19, argument_list; 20, if_statement; 20, 21; 20, 24; 21, comparison_operator:is; 21, 22; 21, 23; 22, identifier:exc_t; 23, None; 24, block; 24, 25; 25, raise_statement; 25, 26; 26, call; 26, 27; 26, 28; 27, identifier:TypeError; 28, argument_list; 28, 29; 29, string:'Must be called in except block.'; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:retry_on_exc; 33, call; 33, 34; 33, 35; 34, identifier:tuple; 35, argument_list; 35, 36; 36, generator_expression; 36, 37; 36, 38; 36, 43; 37, identifier:x; 38, for_in_clause; 38, 39; 38, 40; 39, identifier:x; 40, attribute; 40, 41; 40, 42; 41, identifier:self; 42, identifier:_retry_on; 43, if_clause; 43, 44; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, identifier:inspect; 47, identifier:isclass; 48, argument_list; 48, 49; 49, identifier:x; 50, expression_statement; 50, 51; 51, assignment; 51, 52; 51, 53; 52, identifier:retry_on_codes; 53, call; 53, 54; 53, 55; 54, identifier:tuple; 55, argument_list; 55, 56; 56, generator_expression; 56, 57; 56, 58; 56, 63; 57, identifier:x; 58, for_in_clause; 58, 59; 58, 60; 59, identifier:x; 60, attribute; 60, 61; 60, 62; 61, identifier:self; 62, identifier:_retry_on; 63, if_clause; 63, 64; 64, call; 64, 65; 64, 66; 65, identifier:isinstance; 66, argument_list; 66, 67; 66, 68; 67, identifier:x; 68, identifier:int; 69, if_statement; 69, 70; 69, 75; 69, 100; 70, call; 70, 71; 70, 72; 71, identifier:issubclass; 72, argument_list; 72, 73; 72, 74; 73, identifier:exc_t; 74, identifier:ZendeskError; 75, block; 75, 76; 75, 82; 76, expression_statement; 76, 77; 77, assignment; 77, 78; 77, 79; 78, identifier:code; 79, attribute; 79, 80; 79, 81; 80, identifier:exc_v; 81, identifier:error_code; 82, if_statement; 82, 83; 82, 90; 83, boolean_operator:and; 83, 84; 83, 87; 84, comparison_operator:not; 84, 85; 84, 86; 85, identifier:exc_t; 86, identifier:retry_on_exc; 87, comparison_operator:not; 87, 88; 87, 89; 88, identifier:code; 89, identifier:retry_on_codes; 90, block; 90, 91; 91, expression_statement; 91, 92; 92, call; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:six; 95, identifier:reraise; 96, argument_list; 96, 97; 96, 98; 96, 99; 97, identifier:exc_t; 98, identifier:exc_v; 99, identifier:exc_tb; 100, else_clause; 100, 101; 101, block; 101, 102; 102, if_statement; 102, 103; 102, 109; 103, not_operator; 103, 104; 104, call; 104, 105; 104, 106; 105, identifier:issubclass; 106, argument_list; 106, 107; 106, 108; 107, identifier:exc_t; 108, identifier:retry_on_exc; 109, block; 109, 110; 110, expression_statement; 110, 111; 111, call; 111, 112; 111, 115; 112, attribute; 112, 113; 112, 114; 113, identifier:six; 114, identifier:reraise; 115, argument_list; 115, 116; 115, 117; 115, 118; 116, identifier:exc_t; 117, identifier:exc_v; 118, identifier:exc_tb; 119, if_statement; 119, 120; 119, 123; 120, comparison_operator:is; 120, 121; 120, 122; 121, identifier:resp; 122, None; 123, block; 123, 124; 124, try_statement; 124, 125; 124, 148; 125, block; 125, 126; 125, 141; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:retry_after; 129, call; 129, 130; 129, 131; 130, identifier:float; 131, argument_list; 131, 132; 132, call; 132, 133; 132, 138; 133, attribute; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:resp; 136, identifier:headers; 137, identifier:get; 138, argument_list; 138, 139; 138, 140; 139, string:'Retry-After'; 140, integer:0; 141, expression_statement; 141, 142; 142, call; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:time; 145, identifier:sleep; 146, argument_list; 146, 147; 147, identifier:retry_after; 148, except_clause; 148, 149; 148, 152; 149, tuple; 149, 150; 149, 151; 150, identifier:TypeError; 151, identifier:ValueError; 152, block; 152, 153; 153, pass_statement; 154, return_statement; 154, 155; 155, True
def _handle_retry(self, resp): """Handle any exceptions during API request or parsing its response status code. Parameters: resp: requests.Response instance obtained during concerning request or None, when request failed Returns: True if should retry our request or raises original Exception """ exc_t, exc_v, exc_tb = sys.exc_info() if exc_t is None: raise TypeError('Must be called in except block.') retry_on_exc = tuple( (x for x in self._retry_on if inspect.isclass(x))) retry_on_codes = tuple( (x for x in self._retry_on if isinstance(x, int))) if issubclass(exc_t, ZendeskError): code = exc_v.error_code if exc_t not in retry_on_exc and code not in retry_on_codes: six.reraise(exc_t, exc_v, exc_tb) else: if not issubclass(exc_t, retry_on_exc): six.reraise(exc_t, exc_v, exc_tb) if resp is not None: try: retry_after = float(resp.headers.get('Retry-After', 0)) time.sleep(retry_after) except (TypeError, ValueError): pass return True
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:get_event_triggers; 3, parameters; 3, 4; 4, identifier:self; 5, block; 5, 6; 5, 8; 5, 12; 5, 16; 5, 20; 5, 28; 5, 108; 5, 118; 5, 119; 5, 361; 5, 378; 5, 391; 5, 399; 5, 407; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:events; 11, dictionary; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:nvrflag; 15, False; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:event_xml; 19, list:[]; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:url; 23, binary_operator:%; 23, 24; 23, 25; 24, string:'%s/ISAPI/Event/triggers'; 25, attribute; 25, 26; 25, 27; 26, identifier:self; 27, identifier:root_url; 28, try_statement; 28, 29; 28, 82; 29, block; 29, 30; 29, 44; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:response; 33, call; 33, 34; 33, 39; 34, attribute; 34, 35; 34, 38; 35, attribute; 35, 36; 35, 37; 36, identifier:self; 37, identifier:hik_request; 38, identifier:get; 39, argument_list; 39, 40; 39, 41; 40, identifier:url; 41, keyword_argument; 41, 42; 41, 43; 42, identifier:timeout; 43, identifier:CONNECT_TIMEOUT; 44, if_statement; 44, 45; 44, 54; 44, 55; 45, comparison_operator:==; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:response; 48, identifier:status_code; 49, attribute; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:requests; 52, identifier:codes; 53, identifier:not_found; 54, comment; 55, block; 55, 56; 55, 63; 55, 71; 56, expression_statement; 56, 57; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:_LOGGING; 60, identifier:debug; 61, argument_list; 61, 62; 62, string:'Using alternate triggers URL.'; 63, expression_statement; 63, 64; 64, assignment; 64, 65; 64, 66; 65, identifier:url; 66, binary_operator:%; 66, 67; 66, 68; 67, string:'%s/Event/triggers'; 68, attribute; 68, 69; 68, 70; 69, identifier:self; 70, identifier:root_url; 71, expression_statement; 71, 72; 72, assignment; 72, 73; 72, 74; 73, identifier:response; 74, call; 74, 75; 74, 80; 75, attribute; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:self; 78, identifier:hik_request; 79, identifier:get; 80, argument_list; 80, 81; 81, identifier:url; 82, except_clause; 82, 83; 82, 97; 83, as_pattern; 83, 84; 83, 95; 84, tuple; 84, 85; 84, 90; 85, attribute; 85, 86; 85, 89; 86, attribute; 86, 87; 86, 88; 87, identifier:requests; 88, identifier:exceptions; 89, identifier:RequestException; 90, attribute; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:requests; 93, identifier:exceptions; 94, identifier:ConnectionError; 95, as_pattern_target; 95, 96; 96, identifier:err; 97, block; 97, 98; 97, 106; 98, expression_statement; 98, 99; 99, call; 99, 100; 99, 103; 100, attribute; 100, 101; 100, 102; 101, identifier:_LOGGING; 102, identifier:error; 103, argument_list; 103, 104; 103, 105; 104, string:'Unable to fetch events, error: %s'; 105, identifier:err; 106, return_statement; 106, 107; 107, None; 108, if_statement; 108, 109; 108, 114; 108, 115; 109, comparison_operator:!=; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:response; 112, identifier:status_code; 113, integer:200; 114, comment; 115, block; 115, 116; 116, return_statement; 116, 117; 117, None; 118, comment; 119, try_statement; 119, 120; 119, 341; 120, block; 120, 121; 120, 132; 120, 191; 121, expression_statement; 121, 122; 122, assignment; 122, 123; 122, 124; 123, identifier:content; 124, call; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:ET; 127, identifier:fromstring; 128, argument_list; 128, 129; 129, attribute; 129, 130; 129, 131; 130, identifier:response; 131, identifier:text; 132, if_statement; 132, 133; 132, 146; 132, 163; 133, call; 133, 134; 133, 139; 134, attribute; 134, 135; 134, 138; 135, subscript; 135, 136; 135, 137; 136, identifier:content; 137, integer:0; 138, identifier:find; 139, argument_list; 139, 140; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:self; 143, identifier:element_query; 144, argument_list; 144, 145; 145, string:'EventTrigger'; 146, block; 146, 147; 147, expression_statement; 147, 148; 148, assignment; 148, 149; 148, 150; 149, identifier:event_xml; 150, call; 150, 151; 150, 156; 151, attribute; 151, 152; 151, 155; 152, subscript; 152, 153; 152, 154; 153, identifier:content; 154, integer:0; 155, identifier:findall; 156, argument_list; 156, 157; 157, call; 157, 158; 157, 161; 158, attribute; 158, 159; 158, 160; 159, identifier:self; 160, identifier:element_query; 161, argument_list; 161, 162; 162, string:'EventTrigger'; 163, elif_clause; 163, 164; 163, 175; 163, 176; 164, call; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:content; 167, identifier:find; 168, argument_list; 168, 169; 169, call; 169, 170; 169, 173; 170, attribute; 170, 171; 170, 172; 171, identifier:self; 172, identifier:element_query; 173, argument_list; 173, 174; 174, string:'EventTrigger'; 175, comment; 176, block; 176, 177; 177, expression_statement; 177, 178; 178, assignment; 178, 179; 178, 180; 179, identifier:event_xml; 180, call; 180, 181; 180, 184; 181, attribute; 181, 182; 181, 183; 182, identifier:content; 183, identifier:findall; 184, argument_list; 184, 185; 185, call; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:self; 188, identifier:element_query; 189, argument_list; 189, 190; 190, string:'EventTrigger'; 191, for_statement; 191, 192; 191, 193; 191, 194; 192, identifier:eventtrigger; 193, identifier:event_xml; 194, block; 194, 195; 194, 209; 194, 210; 194, 216; 194, 230; 194, 234; 194, 238; 194, 289; 195, expression_statement; 195, 196; 196, assignment; 196, 197; 196, 198; 197, identifier:ettype; 198, call; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, identifier:eventtrigger; 201, identifier:find; 202, argument_list; 202, 203; 203, call; 203, 204; 203, 207; 204, attribute; 204, 205; 204, 206; 205, identifier:self; 206, identifier:element_query; 207, argument_list; 207, 208; 208, string:'eventType'; 209, comment; 210, if_statement; 210, 211; 210, 214; 211, comparison_operator:is; 211, 212; 211, 213; 212, identifier:ettype; 213, None; 214, block; 214, 215; 215, break_statement; 216, expression_statement; 216, 217; 217, assignment; 217, 218; 217, 219; 218, identifier:etnotify; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:eventtrigger; 222, identifier:find; 223, argument_list; 223, 224; 224, call; 224, 225; 224, 228; 225, attribute; 225, 226; 225, 227; 226, identifier:self; 227, identifier:element_query; 228, argument_list; 228, 229; 229, string:'EventTriggerNotificationList'; 230, expression_statement; 230, 231; 231, assignment; 231, 232; 231, 233; 232, identifier:etchannel; 233, None; 234, expression_statement; 234, 235; 235, assignment; 235, 236; 235, 237; 236, identifier:etchannel_num; 237, integer:0; 238, for_statement; 238, 239; 238, 240; 238, 241; 239, identifier:node_name; 240, identifier:CHANNEL_NAMES; 241, block; 241, 242; 241, 256; 242, expression_statement; 242, 243; 243, assignment; 243, 244; 243, 245; 244, identifier:etchannel; 245, call; 245, 246; 245, 249; 246, attribute; 246, 247; 246, 248; 247, identifier:eventtrigger; 248, identifier:find; 249, argument_list; 249, 250; 250, call; 250, 251; 250, 254; 251, attribute; 251, 252; 251, 253; 252, identifier:self; 253, identifier:element_query; 254, argument_list; 254, 255; 255, identifier:node_name; 256, if_statement; 256, 257; 256, 260; 257, comparison_operator:is; 257, 258; 257, 259; 258, identifier:etchannel; 259, None; 260, block; 260, 261; 261, try_statement; 261, 262; 261, 263; 261, 284; 262, comment; 263, block; 263, 264; 263, 273; 263, 283; 264, expression_statement; 264, 265; 265, assignment; 265, 266; 265, 267; 266, identifier:etchannel_num; 267, call; 267, 268; 267, 269; 268, identifier:int; 269, argument_list; 269, 270; 270, attribute; 270, 271; 270, 272; 271, identifier:etchannel; 272, identifier:text; 273, if_statement; 273, 274; 273, 277; 273, 278; 274, comparison_operator:>; 274, 275; 274, 276; 275, identifier:etchannel_num; 276, integer:1; 277, comment; 278, block; 278, 279; 279, expression_statement; 279, 280; 280, assignment; 280, 281; 280, 282; 281, identifier:nvrflag; 282, True; 283, break_statement; 284, except_clause; 284, 285; 284, 286; 284, 287; 285, identifier:ValueError; 286, comment; 287, block; 287, 288; 288, pass_statement; 289, if_statement; 289, 290; 289, 291; 290, identifier:etnotify; 291, block; 291, 292; 292, for_statement; 292, 293; 292, 294; 292, 295; 293, identifier:notifytrigger; 294, identifier:etnotify; 295, block; 295, 296; 295, 310; 296, expression_statement; 296, 297; 297, assignment; 297, 298; 297, 299; 298, identifier:ntype; 299, call; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, identifier:notifytrigger; 302, identifier:find; 303, argument_list; 303, 304; 304, call; 304, 305; 304, 308; 305, attribute; 305, 306; 305, 307; 306, identifier:self; 307, identifier:element_query; 308, argument_list; 308, 309; 309, string:'notificationMethod'; 310, if_statement; 310, 311; 310, 322; 311, boolean_operator:or; 311, 312; 311, 317; 312, comparison_operator:==; 312, 313; 312, 316; 313, attribute; 313, 314; 313, 315; 314, identifier:ntype; 315, identifier:text; 316, string:'center'; 317, comparison_operator:==; 317, 318; 317, 321; 318, attribute; 318, 319; 318, 320; 319, identifier:ntype; 320, identifier:text; 321, string:'HTTP'; 322, block; 322, 323; 322, 325; 323, expression_statement; 323, 324; 324, comment; 325, expression_statement; 325, 326; 326, call; 326, 327; 326, 339; 327, attribute; 327, 328; 327, 337; 327, 338; 328, call; 328, 329; 328, 332; 329, attribute; 329, 330; 329, 331; 330, identifier:events; 331, identifier:setdefault; 332, argument_list; 332, 333; 332, 336; 333, attribute; 333, 334; 333, 335; 334, identifier:ettype; 335, identifier:text; 336, list:[]; 337, line_continuation:\; 338, identifier:append; 339, argument_list; 339, 340; 340, identifier:etchannel_num; 341, except_clause; 341, 342; 341, 350; 342, as_pattern; 342, 343; 342, 348; 343, tuple; 343, 344; 343, 345; 344, identifier:AttributeError; 345, attribute; 345, 346; 345, 347; 346, identifier:ET; 347, identifier:ParseError; 348, as_pattern_target; 348, 349; 349, identifier:err; 350, block; 350, 351; 350, 359; 351, expression_statement; 351, 352; 352, call; 352, 353; 352, 356; 353, attribute; 353, 354; 353, 355; 354, identifier:_LOGGING; 355, identifier:error; 356, argument_list; 356, 357; 356, 358; 357, string:'There was a problem finding an element: %s'; 358, identifier:err; 359, return_statement; 359, 360; 360, None; 361, if_statement; 361, 362; 361, 363; 361, 370; 362, identifier:nvrflag; 363, block; 363, 364; 364, expression_statement; 364, 365; 365, assignment; 365, 366; 365, 369; 366, attribute; 366, 367; 366, 368; 367, identifier:self; 368, identifier:device_type; 369, identifier:NVR_DEVICE; 370, else_clause; 370, 371; 371, block; 371, 372; 372, expression_statement; 372, 373; 373, assignment; 373, 374; 373, 377; 374, attribute; 374, 375; 374, 376; 375, identifier:self; 376, identifier:device_type; 377, identifier:CAM_DEVICE; 378, expression_statement; 378, 379; 379, call; 379, 380; 379, 383; 380, attribute; 380, 381; 380, 382; 381, identifier:_LOGGING; 382, identifier:debug; 383, argument_list; 383, 384; 383, 385; 383, 388; 384, string:'Processed %s as %s Device.'; 385, attribute; 385, 386; 385, 387; 386, identifier:self; 387, identifier:cam_id; 388, attribute; 388, 389; 388, 390; 389, identifier:self; 390, identifier:device_type; 391, expression_statement; 391, 392; 392, call; 392, 393; 392, 396; 393, attribute; 393, 394; 393, 395; 394, identifier:_LOGGING; 395, identifier:debug; 396, argument_list; 396, 397; 396, 398; 397, string:'Found events: %s'; 398, identifier:events; 399, expression_statement; 399, 400; 400, call; 400, 401; 400, 406; 401, attribute; 401, 402; 401, 405; 402, attribute; 402, 403; 402, 404; 403, identifier:self; 404, identifier:hik_request; 405, identifier:close; 406, argument_list; 407, return_statement; 407, 408; 408, identifier:events
def get_event_triggers(self): """ Returns dict of supported events. Key = Event Type List = Channels that have that event activated """ events = {} nvrflag = False event_xml = [] url = '%s/ISAPI/Event/triggers' % self.root_url try: response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT) if response.status_code == requests.codes.not_found: # Try alternate URL for triggers _LOGGING.debug('Using alternate triggers URL.') url = '%s/Event/triggers' % self.root_url response = self.hik_request.get(url) except (requests.exceptions.RequestException, requests.exceptions.ConnectionError) as err: _LOGGING.error('Unable to fetch events, error: %s', err) return None if response.status_code != 200: # If we didn't recieve 200, abort return None # pylint: disable=too-many-nested-blocks try: content = ET.fromstring(response.text) if content[0].find(self.element_query('EventTrigger')): event_xml = content[0].findall( self.element_query('EventTrigger')) elif content.find(self.element_query('EventTrigger')): # This is either an NVR or a rebadged camera event_xml = content.findall( self.element_query('EventTrigger')) for eventtrigger in event_xml: ettype = eventtrigger.find(self.element_query('eventType')) # Catch empty xml defintions if ettype is None: break etnotify = eventtrigger.find( self.element_query('EventTriggerNotificationList')) etchannel = None etchannel_num = 0 for node_name in CHANNEL_NAMES: etchannel = eventtrigger.find( self.element_query(node_name)) if etchannel is not None: try: # Need to make sure this is actually a number etchannel_num = int(etchannel.text) if etchannel_num > 1: # Must be an nvr nvrflag = True break except ValueError: # Field must not be an integer pass if etnotify: for notifytrigger in etnotify: ntype = notifytrigger.find( self.element_query('notificationMethod')) if ntype.text == 'center' or ntype.text == 'HTTP': """ If we got this far we found an event that we want to track. """ events.setdefault(ettype.text, []) \ .append(etchannel_num) except (AttributeError, ET.ParseError) as err: _LOGGING.error( 'There was a problem finding an element: %s', err) return None if nvrflag: self.device_type = NVR_DEVICE else: self.device_type = CAM_DEVICE _LOGGING.debug('Processed %s as %s Device.', self.cam_id, self.device_type) _LOGGING.debug('Found events: %s', events) self.hik_request.close() return events
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:get_device_info; 3, parameters; 3, 4; 4, identifier:self; 5, block; 5, 6; 5, 8; 5, 12; 5, 20; 5, 24; 5, 207; 5, 227; 5, 248; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:device_info; 11, dictionary; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:url; 15, binary_operator:%; 15, 16; 15, 17; 16, string:'%s/ISAPI/System/deviceInfo'; 17, attribute; 17, 18; 17, 19; 18, identifier:self; 19, identifier:root_url; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:using_digest; 23, False; 24, try_statement; 24, 25; 24, 181; 25, block; 25, 26; 25, 40; 25, 89; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:response; 29, call; 29, 30; 29, 35; 30, attribute; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:hik_request; 34, identifier:get; 35, argument_list; 35, 36; 35, 37; 36, identifier:url; 37, keyword_argument; 37, 38; 37, 39; 38, identifier:timeout; 39, identifier:CONNECT_TIMEOUT; 40, if_statement; 40, 41; 40, 50; 41, comparison_operator:==; 41, 42; 41, 45; 42, attribute; 42, 43; 42, 44; 43, identifier:response; 44, identifier:status_code; 45, attribute; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:requests; 48, identifier:codes; 49, identifier:unauthorized; 50, block; 50, 51; 50, 58; 50, 74; 50, 78; 51, expression_statement; 51, 52; 52, call; 52, 53; 52, 56; 53, attribute; 53, 54; 53, 55; 54, identifier:_LOGGING; 55, identifier:debug; 56, argument_list; 56, 57; 57, string:'Basic authentication failed. Using digest.'; 58, expression_statement; 58, 59; 59, assignment; 59, 60; 59, 65; 60, attribute; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:self; 63, identifier:hik_request; 64, identifier:auth; 65, call; 65, 66; 65, 67; 66, identifier:HTTPDigestAuth; 67, argument_list; 67, 68; 67, 71; 68, attribute; 68, 69; 68, 70; 69, identifier:self; 70, identifier:usr; 71, attribute; 71, 72; 71, 73; 72, identifier:self; 73, identifier:pwd; 74, expression_statement; 74, 75; 75, assignment; 75, 76; 75, 77; 76, identifier:using_digest; 77, True; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:response; 81, call; 81, 82; 81, 87; 82, attribute; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:self; 85, identifier:hik_request; 86, identifier:get; 87, argument_list; 87, 88; 88, identifier:url; 89, if_statement; 89, 90; 89, 99; 89, 100; 90, comparison_operator:==; 90, 91; 90, 94; 91, attribute; 91, 92; 91, 93; 92, identifier:response; 93, identifier:status_code; 94, attribute; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:requests; 97, identifier:codes; 98, identifier:not_found; 99, comment; 100, block; 100, 101; 100, 108; 100, 116; 100, 127; 100, 128; 100, 129; 101, expression_statement; 101, 102; 102, call; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:_LOGGING; 105, identifier:debug; 106, argument_list; 106, 107; 107, string:'Using alternate deviceInfo URL.'; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:url; 111, binary_operator:%; 111, 112; 111, 113; 112, string:'%s/System/deviceInfo'; 113, attribute; 113, 114; 113, 115; 114, identifier:self; 115, identifier:root_url; 116, expression_statement; 116, 117; 117, assignment; 117, 118; 117, 119; 118, identifier:response; 119, call; 119, 120; 119, 125; 120, attribute; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:self; 123, identifier:hik_request; 124, identifier:get; 125, argument_list; 125, 126; 126, identifier:url; 127, comment; 128, comment; 129, if_statement; 129, 130; 129, 142; 130, boolean_operator:and; 130, 131; 130, 133; 131, not_operator; 131, 132; 132, identifier:using_digest; 133, comparison_operator:==; 133, 134; 133, 137; 134, attribute; 134, 135; 134, 136; 135, identifier:response; 136, identifier:status_code; 137, attribute; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:requests; 140, identifier:codes; 141, identifier:unauthorized; 142, block; 142, 143; 142, 150; 142, 166; 142, 170; 143, expression_statement; 143, 144; 144, call; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:_LOGGING; 147, identifier:debug; 148, argument_list; 148, 149; 149, string:'Basic authentication failed. Using digest.'; 150, expression_statement; 150, 151; 151, assignment; 151, 152; 151, 157; 152, attribute; 152, 153; 152, 156; 153, attribute; 153, 154; 153, 155; 154, identifier:self; 155, identifier:hik_request; 156, identifier:auth; 157, call; 157, 158; 157, 159; 158, identifier:HTTPDigestAuth; 159, argument_list; 159, 160; 159, 163; 160, attribute; 160, 161; 160, 162; 161, identifier:self; 162, identifier:usr; 163, attribute; 163, 164; 163, 165; 164, identifier:self; 165, identifier:pwd; 166, expression_statement; 166, 167; 167, assignment; 167, 168; 167, 169; 168, identifier:using_digest; 169, True; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 173; 172, identifier:response; 173, call; 173, 174; 173, 179; 174, attribute; 174, 175; 174, 178; 175, attribute; 175, 176; 175, 177; 176, identifier:self; 177, identifier:hik_request; 178, identifier:get; 179, argument_list; 179, 180; 180, identifier:url; 181, except_clause; 181, 182; 181, 196; 182, as_pattern; 182, 183; 182, 194; 183, tuple; 183, 184; 183, 189; 184, attribute; 184, 185; 184, 188; 185, attribute; 185, 186; 185, 187; 186, identifier:requests; 187, identifier:exceptions; 188, identifier:RequestException; 189, attribute; 189, 190; 189, 193; 190, attribute; 190, 191; 190, 192; 191, identifier:requests; 192, identifier:exceptions; 193, identifier:ConnectionError; 194, as_pattern_target; 194, 195; 195, identifier:err; 196, block; 196, 197; 196, 205; 197, expression_statement; 197, 198; 198, call; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, identifier:_LOGGING; 201, identifier:error; 202, argument_list; 202, 203; 202, 204; 203, string:'Unable to fetch deviceInfo, error: %s'; 204, identifier:err; 205, return_statement; 205, 206; 206, None; 207, if_statement; 207, 208; 207, 217; 208, comparison_operator:==; 208, 209; 208, 212; 209, attribute; 209, 210; 209, 211; 210, identifier:response; 211, identifier:status_code; 212, attribute; 212, 213; 212, 216; 213, attribute; 213, 214; 213, 215; 214, identifier:requests; 215, identifier:codes; 216, identifier:unauthorized; 217, block; 217, 218; 217, 225; 218, expression_statement; 218, 219; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:_LOGGING; 222, identifier:error; 223, argument_list; 223, 224; 224, string:'Authentication failed'; 225, return_statement; 225, 226; 226, None; 227, if_statement; 227, 228; 227, 237; 227, 238; 228, comparison_operator:!=; 228, 229; 228, 232; 229, attribute; 229, 230; 229, 231; 230, identifier:response; 231, identifier:status_code; 232, attribute; 232, 233; 232, 236; 233, attribute; 233, 234; 233, 235; 234, identifier:requests; 235, identifier:codes; 236, identifier:ok; 237, comment; 238, block; 238, 239; 238, 246; 239, expression_statement; 239, 240; 240, call; 240, 241; 240, 244; 241, attribute; 241, 242; 241, 243; 242, identifier:_LOGGING; 243, identifier:debug; 244, argument_list; 244, 245; 245, string:'Unable to fetch device info.'; 246, return_statement; 246, 247; 247, None; 248, try_statement; 248, 249; 248, 331; 249, block; 249, 250; 249, 261; 249, 262; 249, 280; 249, 294; 249, 304; 249, 329; 250, expression_statement; 250, 251; 251, assignment; 251, 252; 251, 253; 252, identifier:tree; 253, call; 253, 254; 253, 257; 254, attribute; 254, 255; 254, 256; 255, identifier:ET; 256, identifier:fromstring; 257, argument_list; 257, 258; 258, attribute; 258, 259; 258, 260; 259, identifier:response; 260, identifier:text; 261, comment; 262, expression_statement; 262, 263; 263, assignment; 263, 264; 263, 265; 264, identifier:nmsp; 265, call; 265, 266; 265, 278; 266, attribute; 266, 267; 266, 277; 267, subscript; 267, 268; 267, 276; 268, call; 268, 269; 268, 274; 269, attribute; 269, 270; 269, 273; 270, attribute; 270, 271; 270, 272; 271, identifier:tree; 272, identifier:tag; 273, identifier:split; 274, argument_list; 274, 275; 275, string:'}'; 276, integer:0; 277, identifier:strip; 278, argument_list; 278, 279; 279, string:'{'; 280, expression_statement; 280, 281; 281, assignment; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:self; 284, identifier:namespace; 285, conditional_expression:if; 285, 286; 285, 287; 285, 293; 286, identifier:nmsp; 287, call; 287, 288; 287, 291; 288, attribute; 288, 289; 288, 290; 289, identifier:nmsp; 290, identifier:startswith; 291, argument_list; 291, 292; 292, string:'http'; 293, identifier:XML_NAMESPACE; 294, expression_statement; 294, 295; 295, call; 295, 296; 295, 299; 296, attribute; 296, 297; 296, 298; 297, identifier:_LOGGING; 298, identifier:debug; 299, argument_list; 299, 300; 299, 301; 300, string:'Using Namespace: %s'; 301, attribute; 301, 302; 301, 303; 302, identifier:self; 303, identifier:namespace; 304, for_statement; 304, 305; 304, 306; 304, 307; 305, identifier:item; 306, identifier:tree; 307, block; 307, 308; 307, 321; 308, expression_statement; 308, 309; 309, assignment; 309, 310; 309, 311; 310, identifier:tag; 311, subscript; 311, 312; 311, 320; 312, call; 312, 313; 312, 318; 313, attribute; 313, 314; 313, 317; 314, attribute; 314, 315; 314, 316; 315, identifier:item; 316, identifier:tag; 317, identifier:split; 318, argument_list; 318, 319; 319, string:'}'; 320, integer:1; 321, expression_statement; 321, 322; 322, assignment; 322, 323; 322, 326; 323, subscript; 323, 324; 323, 325; 324, identifier:device_info; 325, identifier:tag; 326, attribute; 326, 327; 326, 328; 327, identifier:item; 328, identifier:text; 329, return_statement; 329, 330; 330, identifier:device_info; 331, except_clause; 331, 332; 331, 336; 332, as_pattern; 332, 333; 332, 334; 333, identifier:AttributeError; 334, as_pattern_target; 334, 335; 335, identifier:err; 336, block; 336, 337; 336, 347; 336, 355; 337, expression_statement; 337, 338; 338, call; 338, 339; 338, 342; 339, attribute; 339, 340; 339, 341; 340, identifier:_LOGGING; 341, identifier:error; 342, argument_list; 342, 343; 342, 344; 343, string:'Entire response: %s'; 344, attribute; 344, 345; 344, 346; 345, identifier:response; 346, identifier:text; 347, expression_statement; 347, 348; 348, call; 348, 349; 348, 352; 349, attribute; 349, 350; 349, 351; 350, identifier:_LOGGING; 351, identifier:error; 352, argument_list; 352, 353; 352, 354; 353, string:'There was a problem: %s'; 354, identifier:err; 355, return_statement; 355, 356; 356, None
def get_device_info(self): """Parse deviceInfo into dictionary.""" device_info = {} url = '%s/ISAPI/System/deviceInfo' % self.root_url using_digest = False try: response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT) if response.status_code == requests.codes.unauthorized: _LOGGING.debug('Basic authentication failed. Using digest.') self.hik_request.auth = HTTPDigestAuth(self.usr, self.pwd) using_digest = True response = self.hik_request.get(url) if response.status_code == requests.codes.not_found: # Try alternate URL for deviceInfo _LOGGING.debug('Using alternate deviceInfo URL.') url = '%s/System/deviceInfo' % self.root_url response = self.hik_request.get(url) # Seems to be difference between camera and nvr, they can't seem to # agree if they should 404 or 401 first if not using_digest and response.status_code == requests.codes.unauthorized: _LOGGING.debug('Basic authentication failed. Using digest.') self.hik_request.auth = HTTPDigestAuth(self.usr, self.pwd) using_digest = True response = self.hik_request.get(url) except (requests.exceptions.RequestException, requests.exceptions.ConnectionError) as err: _LOGGING.error('Unable to fetch deviceInfo, error: %s', err) return None if response.status_code == requests.codes.unauthorized: _LOGGING.error('Authentication failed') return None if response.status_code != requests.codes.ok: # If we didn't receive 200, abort _LOGGING.debug('Unable to fetch device info.') return None try: tree = ET.fromstring(response.text) # Try to fetch namespace from XML nmsp = tree.tag.split('}')[0].strip('{') self.namespace = nmsp if nmsp.startswith('http') else XML_NAMESPACE _LOGGING.debug('Using Namespace: %s', self.namespace) for item in tree: tag = item.tag.split('}')[1] device_info[tag] = item.text return device_info except AttributeError as err: _LOGGING.error('Entire response: %s', response.text) _LOGGING.error('There was a problem: %s', err) return None
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:alert_stream; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:reset_event; 6, identifier:kill_event; 7, block; 7, 8; 7, 10; 7, 23; 7, 27; 7, 31; 7, 35; 7, 43; 7, 44; 8, expression_statement; 8, 9; 9, comment; 10, expression_statement; 10, 11; 11, call; 11, 12; 11, 15; 12, attribute; 12, 13; 12, 14; 13, identifier:_LOGGING; 14, identifier:debug; 15, argument_list; 15, 16; 15, 17; 15, 20; 16, string:'Stream Thread Started: %s, %s'; 17, attribute; 17, 18; 17, 19; 18, identifier:self; 19, identifier:name; 20, attribute; 20, 21; 20, 22; 21, identifier:self; 22, identifier:cam_id; 23, expression_statement; 23, 24; 24, assignment; 24, 25; 24, 26; 25, identifier:start_event; 26, False; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:parse_string; 30, string:""; 31, expression_statement; 31, 32; 32, assignment; 32, 33; 32, 34; 33, identifier:fail_count; 34, integer:0; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:url; 38, binary_operator:%; 38, 39; 38, 40; 39, string:'%s/ISAPI/Event/notification/alertStream'; 40, attribute; 40, 41; 40, 42; 41, identifier:self; 42, identifier:root_url; 43, comment; 44, while_statement; 44, 45; 44, 46; 45, True; 46, block; 46, 47; 47, try_statement; 47, 48; 47, 314; 48, block; 48, 49; 48, 68; 48, 102; 48, 142; 48, 266; 49, expression_statement; 49, 50; 50, assignment; 50, 51; 50, 52; 51, identifier:stream; 52, call; 52, 53; 52, 58; 53, attribute; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:self; 56, identifier:hik_request; 57, identifier:get; 58, argument_list; 58, 59; 58, 60; 58, 63; 59, identifier:url; 60, keyword_argument; 60, 61; 60, 62; 61, identifier:stream; 62, True; 63, keyword_argument; 63, 64; 63, 65; 64, identifier:timeout; 65, tuple; 65, 66; 65, 67; 66, identifier:CONNECT_TIMEOUT; 67, identifier:READ_TIMEOUT; 68, if_statement; 68, 69; 68, 78; 68, 79; 69, comparison_operator:==; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:stream; 72, identifier:status_code; 73, attribute; 73, 74; 73, 77; 74, attribute; 74, 75; 74, 76; 75, identifier:requests; 76, identifier:codes; 77, identifier:not_found; 78, comment; 79, block; 79, 80; 79, 88; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:url; 83, binary_operator:%; 83, 84; 83, 85; 84, string:'%s/Event/notification/alertStream'; 85, attribute; 85, 86; 85, 87; 86, identifier:self; 87, identifier:root_url; 88, expression_statement; 88, 89; 89, assignment; 89, 90; 89, 91; 90, identifier:stream; 91, call; 91, 92; 91, 97; 92, attribute; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:self; 95, identifier:hik_request; 96, identifier:get; 97, argument_list; 97, 98; 97, 99; 98, identifier:url; 99, keyword_argument; 99, 100; 99, 101; 100, identifier:stream; 101, True; 102, if_statement; 102, 103; 102, 112; 102, 118; 103, comparison_operator:!=; 103, 104; 103, 107; 104, attribute; 104, 105; 104, 106; 105, identifier:stream; 106, identifier:status_code; 107, attribute; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:requests; 110, identifier:codes; 111, identifier:ok; 112, block; 112, 113; 113, raise_statement; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:ValueError; 116, argument_list; 116, 117; 117, string:'Connection unsucessful.'; 118, else_clause; 118, 119; 119, block; 119, 120; 119, 130; 119, 134; 120, expression_statement; 120, 121; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:_LOGGING; 124, identifier:debug; 125, argument_list; 125, 126; 125, 127; 126, string:'%s Connection Successful.'; 127, attribute; 127, 128; 127, 129; 128, identifier:self; 129, identifier:name; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 133; 132, identifier:fail_count; 133, integer:0; 134, expression_statement; 134, 135; 135, call; 135, 136; 135, 141; 136, attribute; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:self; 139, identifier:watchdog; 140, identifier:start; 141, argument_list; 142, for_statement; 142, 143; 142, 144; 142, 149; 142, 150; 142, 151; 143, identifier:line; 144, call; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:stream; 147, identifier:iter_lines; 148, argument_list; 149, comment; 150, comment; 151, block; 151, 152; 151, 244; 152, if_statement; 152, 153; 152, 154; 153, identifier:line; 154, block; 154, 155; 154, 165; 154, 166; 155, expression_statement; 155, 156; 156, assignment; 156, 157; 156, 158; 157, identifier:str_line; 158, call; 158, 159; 158, 162; 159, attribute; 159, 160; 159, 161; 160, identifier:line; 161, identifier:decode; 162, argument_list; 162, 163; 162, 164; 163, string:"utf-8"; 164, string:"ignore"; 165, comment; 166, if_statement; 166, 167; 166, 176; 166, 177; 166, 186; 166, 235; 167, comparison_operator:!=; 167, 168; 167, 174; 168, call; 168, 169; 168, 172; 169, attribute; 169, 170; 169, 171; 170, identifier:str_line; 171, identifier:find; 172, argument_list; 172, 173; 173, string:'<EventNotificationAlert'; 174, unary_operator:-; 174, 175; 175, integer:1; 176, comment; 177, block; 177, 178; 177, 182; 178, expression_statement; 178, 179; 179, assignment; 179, 180; 179, 181; 180, identifier:start_event; 181, True; 182, expression_statement; 182, 183; 183, augmented_assignment:+=; 183, 184; 183, 185; 184, identifier:parse_string; 185, identifier:str_line; 186, elif_clause; 186, 187; 186, 196; 186, 197; 187, comparison_operator:!=; 187, 188; 187, 194; 188, call; 188, 189; 188, 192; 189, attribute; 189, 190; 189, 191; 190, identifier:str_line; 191, identifier:find; 192, argument_list; 192, 193; 193, string:'</EventNotificationAlert>'; 194, unary_operator:-; 194, 195; 195, integer:1; 196, comment; 197, block; 197, 198; 197, 202; 197, 206; 198, expression_statement; 198, 199; 199, augmented_assignment:+=; 199, 200; 199, 201; 200, identifier:parse_string; 201, identifier:str_line; 202, expression_statement; 202, 203; 203, assignment; 203, 204; 203, 205; 204, identifier:start_event; 205, False; 206, if_statement; 206, 207; 206, 208; 207, identifier:parse_string; 208, block; 208, 209; 208, 218; 208, 225; 208, 231; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 212; 211, identifier:tree; 212, call; 212, 213; 212, 216; 213, attribute; 213, 214; 213, 215; 214, identifier:ET; 215, identifier:fromstring; 216, argument_list; 216, 217; 217, identifier:parse_string; 218, expression_statement; 218, 219; 219, call; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:self; 222, identifier:process_stream; 223, argument_list; 223, 224; 224, identifier:tree; 225, expression_statement; 225, 226; 226, call; 226, 227; 226, 230; 227, attribute; 227, 228; 227, 229; 228, identifier:self; 229, identifier:update_stale; 230, argument_list; 231, expression_statement; 231, 232; 232, assignment; 232, 233; 232, 234; 233, identifier:parse_string; 234, string:""; 235, else_clause; 235, 236; 236, block; 236, 237; 237, if_statement; 237, 238; 237, 239; 238, identifier:start_event; 239, block; 239, 240; 240, expression_statement; 240, 241; 241, augmented_assignment:+=; 241, 242; 241, 243; 242, identifier:parse_string; 243, identifier:str_line; 244, if_statement; 244, 245; 244, 250; 244, 251; 244, 253; 245, call; 245, 246; 245, 249; 246, attribute; 246, 247; 246, 248; 247, identifier:kill_event; 248, identifier:is_set; 249, argument_list; 250, comment; 251, block; 251, 252; 252, break_statement; 253, elif_clause; 253, 254; 253, 259; 253, 260; 254, call; 254, 255; 254, 258; 255, attribute; 255, 256; 255, 257; 256, identifier:reset_event; 257, identifier:is_set; 258, argument_list; 259, comment; 260, block; 260, 261; 261, raise_statement; 261, 262; 262, call; 262, 263; 262, 264; 263, identifier:ValueError; 264, argument_list; 264, 265; 265, string:'Watchdog failed.'; 266, if_statement; 266, 267; 266, 272; 266, 273; 266, 301; 267, call; 267, 268; 267, 271; 268, attribute; 268, 269; 268, 270; 269, identifier:kill_event; 270, identifier:is_set; 271, argument_list; 272, comment; 273, block; 273, 274; 273, 284; 273, 292; 273, 300; 274, expression_statement; 274, 275; 275, call; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:_LOGGING; 278, identifier:debug; 279, argument_list; 279, 280; 279, 281; 280, string:'Stopping event stream thread for %s'; 281, attribute; 281, 282; 281, 283; 282, identifier:self; 283, identifier:name; 284, expression_statement; 284, 285; 285, call; 285, 286; 285, 291; 286, attribute; 286, 287; 286, 290; 287, attribute; 287, 288; 287, 289; 288, identifier:self; 289, identifier:watchdog; 290, identifier:stop; 291, argument_list; 292, expression_statement; 292, 293; 293, call; 293, 294; 293, 299; 294, attribute; 294, 295; 294, 298; 295, attribute; 295, 296; 295, 297; 296, identifier:self; 297, identifier:hik_request; 298, identifier:close; 299, argument_list; 300, return_statement; 301, elif_clause; 301, 302; 301, 307; 301, 308; 302, call; 302, 303; 302, 306; 303, attribute; 303, 304; 303, 305; 304, identifier:reset_event; 305, identifier:is_set; 306, argument_list; 307, comment; 308, block; 308, 309; 309, raise_statement; 309, 310; 310, call; 310, 311; 310, 312; 311, identifier:ValueError; 312, argument_list; 312, 313; 313, string:'Watchdog failed.'; 314, except_clause; 314, 315; 314, 330; 315, as_pattern; 315, 316; 315, 328; 316, tuple; 316, 317; 316, 318; 316, 323; 317, identifier:ValueError; 318, attribute; 318, 319; 318, 322; 319, attribute; 319, 320; 319, 321; 320, identifier:requests; 321, identifier:exceptions; 322, identifier:ConnectionError; 323, attribute; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:requests; 326, identifier:exceptions; 327, identifier:ChunkedEncodingError; 328, as_pattern_target; 328, 329; 329, identifier:err; 330, block; 330, 331; 330, 335; 330, 341; 330, 359; 330, 363; 330, 371; 330, 379; 330, 386; 330, 392; 330, 401; 331, expression_statement; 331, 332; 332, augmented_assignment:+=; 332, 333; 332, 334; 333, identifier:fail_count; 334, integer:1; 335, expression_statement; 335, 336; 336, call; 336, 337; 336, 340; 337, attribute; 337, 338; 337, 339; 338, identifier:reset_event; 339, identifier:clear; 340, argument_list; 341, expression_statement; 341, 342; 342, call; 342, 343; 342, 346; 343, attribute; 343, 344; 343, 345; 344, identifier:_LOGGING; 345, identifier:warning; 346, argument_list; 346, 347; 346, 348; 346, 351; 346, 352; 346, 358; 347, string:'%s Connection Failed (count=%d). Waiting %ss. Err: %s'; 348, attribute; 348, 349; 348, 350; 349, identifier:self; 350, identifier:name; 351, identifier:fail_count; 352, binary_operator:+; 352, 353; 352, 357; 353, parenthesized_expression; 353, 354; 354, binary_operator:*; 354, 355; 354, 356; 355, identifier:fail_count; 356, integer:5; 357, integer:5; 358, identifier:err; 359, expression_statement; 359, 360; 360, assignment; 360, 361; 360, 362; 361, identifier:parse_string; 362, string:""; 363, expression_statement; 363, 364; 364, call; 364, 365; 364, 370; 365, attribute; 365, 366; 365, 369; 366, attribute; 366, 367; 366, 368; 367, identifier:self; 368, identifier:watchdog; 369, identifier:stop; 370, argument_list; 371, expression_statement; 371, 372; 372, call; 372, 373; 372, 378; 373, attribute; 373, 374; 373, 377; 374, attribute; 374, 375; 374, 376; 375, identifier:self; 376, identifier:hik_request; 377, identifier:close; 378, argument_list; 379, expression_statement; 379, 380; 380, call; 380, 381; 380, 384; 381, attribute; 381, 382; 381, 383; 382, identifier:time; 383, identifier:sleep; 384, argument_list; 384, 385; 385, integer:5; 386, expression_statement; 386, 387; 387, call; 387, 388; 387, 391; 388, attribute; 388, 389; 388, 390; 389, identifier:self; 390, identifier:update_stale; 391, argument_list; 392, expression_statement; 392, 393; 393, call; 393, 394; 393, 397; 394, attribute; 394, 395; 394, 396; 395, identifier:time; 396, identifier:sleep; 397, argument_list; 397, 398; 398, binary_operator:*; 398, 399; 398, 400; 399, identifier:fail_count; 400, integer:5; 401, continue_statement
def alert_stream(self, reset_event, kill_event): """Open event stream.""" _LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id) start_event = False parse_string = "" fail_count = 0 url = '%s/ISAPI/Event/notification/alertStream' % self.root_url # pylint: disable=too-many-nested-blocks while True: try: stream = self.hik_request.get(url, stream=True, timeout=(CONNECT_TIMEOUT, READ_TIMEOUT)) if stream.status_code == requests.codes.not_found: # Try alternate URL for stream url = '%s/Event/notification/alertStream' % self.root_url stream = self.hik_request.get(url, stream=True) if stream.status_code != requests.codes.ok: raise ValueError('Connection unsucessful.') else: _LOGGING.debug('%s Connection Successful.', self.name) fail_count = 0 self.watchdog.start() for line in stream.iter_lines(): # _LOGGING.debug('Processing line from %s', self.name) # filter out keep-alive new lines if line: str_line = line.decode("utf-8", "ignore") # New events start with --boundry if str_line.find('<EventNotificationAlert') != -1: # Start of event message start_event = True parse_string += str_line elif str_line.find('</EventNotificationAlert>') != -1: # Message end found found parse_string += str_line start_event = False if parse_string: tree = ET.fromstring(parse_string) self.process_stream(tree) self.update_stale() parse_string = "" else: if start_event: parse_string += str_line if kill_event.is_set(): # We were asked to stop the thread so lets do so. break elif reset_event.is_set(): # We need to reset the connection. raise ValueError('Watchdog failed.') if kill_event.is_set(): # We were asked to stop the thread so lets do so. _LOGGING.debug('Stopping event stream thread for %s', self.name) self.watchdog.stop() self.hik_request.close() return elif reset_event.is_set(): # We need to reset the connection. raise ValueError('Watchdog failed.') except (ValueError, requests.exceptions.ConnectionError, requests.exceptions.ChunkedEncodingError) as err: fail_count += 1 reset_event.clear() _LOGGING.warning('%s Connection Failed (count=%d). Waiting %ss. Err: %s', self.name, fail_count, (fail_count * 5) + 5, err) parse_string = "" self.watchdog.stop() self.hik_request.close() time.sleep(5) self.update_stale() time.sleep(fail_count * 5) continue
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 20; 2, function_name:construct_request; 3, parameters; 3, 4; 3, 5; 3, 8; 3, 11; 3, 14; 3, 17; 4, identifier:ticker; 5, default_parameter; 5, 6; 5, 7; 6, identifier:fields; 7, None; 8, default_parameter; 8, 9; 8, 10; 9, identifier:date; 10, None; 11, default_parameter; 11, 12; 11, 13; 12, identifier:date_from; 13, None; 14, default_parameter; 14, 15; 14, 16; 15, identifier:date_to; 16, None; 17, default_parameter; 17, 18; 17, 19; 18, identifier:freq; 19, None; 20, block; 20, 21; 20, 23; 20, 57; 20, 100; 20, 165; 20, 176; 21, expression_statement; 21, 22; 22, comment; 23, if_statement; 23, 24; 23, 29; 23, 34; 23, 50; 24, call; 24, 25; 24, 26; 25, identifier:isinstance; 26, argument_list; 26, 27; 26, 28; 27, identifier:ticker; 28, identifier:basestring; 29, block; 29, 30; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:request; 33, identifier:ticker; 34, elif_clause; 34, 35; 34, 40; 35, call; 35, 36; 35, 37; 36, identifier:hasattr; 37, argument_list; 37, 38; 37, 39; 38, identifier:ticker; 39, string:'__len__'; 40, block; 40, 41; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:request; 44, call; 44, 45; 44, 48; 45, attribute; 45, 46; 45, 47; 46, string:','; 47, identifier:join; 48, argument_list; 48, 49; 49, identifier:ticker; 50, else_clause; 50, 51; 51, block; 51, 52; 52, raise_statement; 52, 53; 53, call; 53, 54; 53, 55; 54, identifier:ValueError; 55, argument_list; 55, 56; 56, string:'ticker should be either string or list/array of strings'; 57, if_statement; 57, 58; 57, 61; 58, comparison_operator:is; 58, 59; 58, 60; 59, identifier:fields; 60, None; 61, block; 61, 62; 62, if_statement; 62, 63; 62, 68; 62, 75; 63, call; 63, 64; 63, 65; 64, identifier:isinstance; 65, argument_list; 65, 66; 65, 67; 66, identifier:fields; 67, identifier:basestring; 68, block; 68, 69; 69, expression_statement; 69, 70; 70, augmented_assignment:+=; 70, 71; 70, 72; 71, identifier:request; 72, binary_operator:+; 72, 73; 72, 74; 73, string:'~='; 74, identifier:fields; 75, elif_clause; 75, 76; 75, 88; 76, boolean_operator:and; 76, 77; 76, 82; 77, call; 77, 78; 77, 79; 78, identifier:isinstance; 79, argument_list; 79, 80; 79, 81; 80, identifier:fields; 81, identifier:list; 82, comparison_operator:>; 82, 83; 82, 87; 83, call; 83, 84; 83, 85; 84, identifier:len; 85, argument_list; 85, 86; 86, identifier:fields; 87, integer:0; 88, block; 88, 89; 89, expression_statement; 89, 90; 90, augmented_assignment:+=; 90, 91; 90, 92; 91, identifier:request; 92, binary_operator:+; 92, 93; 92, 94; 93, string:'~='; 94, call; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, string:','; 97, identifier:join; 98, argument_list; 98, 99; 99, identifier:fields; 100, if_statement; 100, 101; 100, 104; 100, 121; 101, comparison_operator:is; 101, 102; 101, 103; 102, identifier:date; 103, None; 104, block; 104, 105; 105, expression_statement; 105, 106; 106, augmented_assignment:+=; 106, 107; 106, 108; 107, identifier:request; 108, binary_operator:+; 108, 109; 108, 110; 109, string:'~@'; 110, call; 110, 111; 110, 119; 111, attribute; 111, 112; 111, 118; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:pd; 115, identifier:to_datetime; 116, argument_list; 116, 117; 117, identifier:date; 118, identifier:strftime; 119, argument_list; 119, 120; 120, string:'%Y-%m-%d'; 121, else_clause; 121, 122; 122, block; 122, 123; 122, 144; 123, if_statement; 123, 124; 123, 127; 124, comparison_operator:is; 124, 125; 124, 126; 125, identifier:date_from; 126, None; 127, block; 127, 128; 128, expression_statement; 128, 129; 129, augmented_assignment:+=; 129, 130; 129, 131; 130, identifier:request; 131, binary_operator:+; 131, 132; 131, 133; 132, string:'~'; 133, call; 133, 134; 133, 142; 134, attribute; 134, 135; 134, 141; 135, call; 135, 136; 135, 139; 136, attribute; 136, 137; 136, 138; 137, identifier:pd; 138, identifier:to_datetime; 139, argument_list; 139, 140; 140, identifier:date_from; 141, identifier:strftime; 142, argument_list; 142, 143; 143, string:'%Y-%m-%d'; 144, if_statement; 144, 145; 144, 148; 145, comparison_operator:is; 145, 146; 145, 147; 146, identifier:date_to; 147, None; 148, block; 148, 149; 149, expression_statement; 149, 150; 150, augmented_assignment:+=; 150, 151; 150, 152; 151, identifier:request; 152, binary_operator:+; 152, 153; 152, 154; 153, string:'~:'; 154, call; 154, 155; 154, 163; 155, attribute; 155, 156; 155, 162; 156, call; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:pd; 159, identifier:to_datetime; 160, argument_list; 160, 161; 161, identifier:date_to; 162, identifier:strftime; 163, argument_list; 163, 164; 164, string:'%Y-%m-%d'; 165, if_statement; 165, 166; 165, 169; 166, comparison_operator:is; 166, 167; 166, 168; 167, identifier:freq; 168, None; 169, block; 169, 170; 170, expression_statement; 170, 171; 171, augmented_assignment:+=; 171, 172; 171, 173; 172, identifier:request; 173, binary_operator:+; 173, 174; 173, 175; 174, string:'~'; 175, identifier:freq; 176, return_statement; 176, 177; 177, identifier:request
def construct_request(ticker, fields=None, date=None, date_from=None, date_to=None, freq=None): """Construct a request string for querying TR DWE. tickers - ticker or symbol fields - list of fields. date - date for a single-date query date_from, date_to - date range (used only if "date" is not specified) freq - frequency of data: daily('D'), weekly('W') or monthly('M') Use here 'REP' for static requests Some of available fields: P - adjusted closing price PO - opening price PH - high price PL - low price VO - volume, which is expressed in 1000's of shares. UP - unadjusted price OI - open interest MV - market value EPS - earnings per share DI - dividend index MTVB - market to book value PTVB - price to book value ... The full list of data fields is available at http://dtg.tfn.com/. """ if isinstance(ticker, basestring): request = ticker elif hasattr(ticker, '__len__'): request = ','.join(ticker) else: raise ValueError('ticker should be either string or list/array of strings') if fields is not None: if isinstance(fields, basestring): request += '~=' + fields elif isinstance(fields, list) and len(fields) > 0: request += '~=' + ','.join(fields) if date is not None: request += '~@' + pd.to_datetime(date).strftime('%Y-%m-%d') else: if date_from is not None: request += '~' + pd.to_datetime(date_from).strftime('%Y-%m-%d') if date_to is not None: request += '~:' + pd.to_datetime(date_to).strftime('%Y-%m-%d') if freq is not None: request += '~' + freq return request
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:set; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 4, identifier:self; 5, identifier:name; 6, identifier:value; 7, default_parameter; 7, 8; 7, 9; 8, identifier:index; 9, unary_operator:-; 9, 10; 10, integer:1; 11, block; 11, 12; 11, 14; 11, 15; 11, 32; 11, 40; 11, 56; 11, 75; 11, 144; 11, 158; 11, 168; 11, 190; 11, 191; 12, expression_statement; 12, 13; 13, comment; 14, comment; 15, if_statement; 15, 16; 15, 21; 16, call; 16, 17; 16, 18; 17, identifier:isinstance; 18, argument_list; 18, 19; 18, 20; 19, identifier:value; 20, identifier:ElementProxy; 21, block; 21, 22; 22, expression_statement; 22, 23; 23, assignment; 23, 24; 23, 25; 24, identifier:value; 25, call; 25, 26; 25, 31; 26, attribute; 26, 27; 26, 30; 27, subscript; 27, 28; 27, 29; 28, identifier:value; 29, integer:0; 30, identifier:to_er7; 31, argument_list; 32, expression_statement; 32, 33; 33, assignment; 33, 34; 33, 35; 34, identifier:name; 35, call; 35, 36; 35, 39; 36, attribute; 36, 37; 36, 38; 37, identifier:name; 38, identifier:upper; 39, argument_list; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:reference; 43, conditional_expression:if; 43, 44; 43, 45; 43, 48; 44, None; 45, comparison_operator:is; 45, 46; 45, 47; 46, identifier:name; 47, None; 48, call; 48, 49; 48, 54; 49, attribute; 49, 50; 49, 53; 50, attribute; 50, 51; 50, 52; 51, identifier:self; 52, identifier:element; 53, identifier:find_child_reference; 54, argument_list; 54, 55; 55, identifier:name; 56, expression_statement; 56, 57; 57, assignment; 57, 58; 57, 61; 58, pattern_list; 58, 59; 58, 60; 59, identifier:child_ref; 60, identifier:child_name; 61, conditional_expression:if; 61, 62; 61, 65; 61, 68; 62, tuple; 62, 63; 62, 64; 63, None; 64, None; 65, comparison_operator:is; 65, 66; 65, 67; 66, identifier:reference; 67, None; 68, tuple; 68, 69; 68, 72; 69, subscript; 69, 70; 69, 71; 70, identifier:reference; 71, string:'ref'; 72, subscript; 72, 73; 72, 74; 73, identifier:reference; 74, string:'name'; 75, if_statement; 75, 76; 75, 81; 75, 82; 75, 100; 75, 112; 75, 136; 76, call; 76, 77; 76, 78; 77, identifier:isinstance; 78, argument_list; 78, 79; 78, 80; 79, identifier:value; 80, identifier:basestring; 81, comment; 82, block; 82, 83; 83, expression_statement; 83, 84; 84, assignment; 84, 85; 84, 86; 85, identifier:child; 86, call; 86, 87; 86, 92; 87, attribute; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:self; 90, identifier:element; 91, identifier:parse_child; 92, argument_list; 92, 93; 92, 94; 92, 97; 93, identifier:value; 94, keyword_argument; 94, 95; 94, 96; 95, identifier:child_name; 96, identifier:child_name; 97, keyword_argument; 97, 98; 97, 99; 98, identifier:reference; 99, identifier:child_ref; 100, elif_clause; 100, 101; 100, 106; 100, 107; 101, call; 101, 102; 101, 103; 102, identifier:isinstance; 103, argument_list; 103, 104; 103, 105; 104, identifier:value; 105, identifier:Element; 106, comment; 107, block; 107, 108; 108, expression_statement; 108, 109; 109, assignment; 109, 110; 109, 111; 110, identifier:child; 111, identifier:value; 112, elif_clause; 112, 113; 112, 118; 113, call; 113, 114; 113, 115; 114, identifier:isinstance; 115, argument_list; 115, 116; 115, 117; 116, identifier:value; 117, identifier:BaseDataType; 118, block; 118, 119; 118, 130; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:child; 122, call; 122, 123; 122, 126; 123, attribute; 123, 124; 123, 125; 124, identifier:self; 125, identifier:create_element; 126, argument_list; 126, 127; 126, 128; 126, 129; 127, identifier:name; 128, False; 129, identifier:reference; 130, expression_statement; 130, 131; 131, assignment; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:child; 134, identifier:value; 135, identifier:value; 136, else_clause; 136, 137; 137, block; 137, 138; 138, raise_statement; 138, 139; 139, call; 139, 140; 139, 141; 140, identifier:ChildNotValid; 141, argument_list; 141, 142; 141, 143; 142, identifier:value; 143, identifier:child_name; 144, if_statement; 144, 145; 144, 150; 144, 151; 145, comparison_operator:!=; 145, 146; 145, 149; 146, attribute; 146, 147; 146, 148; 147, identifier:child; 148, identifier:name; 149, identifier:child_name; 150, comment; 151, block; 151, 152; 152, raise_statement; 152, 153; 153, call; 153, 154; 153, 155; 154, identifier:ChildNotValid; 155, argument_list; 155, 156; 155, 157; 156, identifier:value; 157, identifier:child_name; 158, expression_statement; 158, 159; 159, assignment; 159, 160; 159, 161; 160, identifier:child_to_remove; 161, call; 161, 162; 161, 165; 162, attribute; 162, 163; 162, 164; 163, identifier:self; 164, identifier:child_at_index; 165, argument_list; 165, 166; 165, 167; 166, identifier:child_name; 167, identifier:index; 168, if_statement; 168, 169; 168, 172; 168, 180; 169, comparison_operator:is; 169, 170; 169, 171; 170, identifier:child_to_remove; 171, None; 172, block; 172, 173; 173, expression_statement; 173, 174; 174, call; 174, 175; 174, 178; 175, attribute; 175, 176; 175, 177; 176, identifier:self; 177, identifier:append; 178, argument_list; 178, 179; 179, identifier:child; 180, else_clause; 180, 181; 181, block; 181, 182; 182, expression_statement; 182, 183; 183, call; 183, 184; 183, 187; 184, attribute; 184, 185; 184, 186; 185, identifier:self; 186, identifier:replace_child; 187, argument_list; 187, 188; 187, 189; 188, identifier:child_to_remove; 189, identifier:child; 190, comment; 191, expression_statement; 191, 192; 192, call; 192, 193; 192, 198; 193, attribute; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:self; 196, identifier:element; 197, identifier:set_parent_to_traversal; 198, argument_list
def set(self, name, value, index=-1): """ Assign the ``value`` to the child having the given ``name`` at the ``index`` position :type name: ``str`` :param name: the child name (e.g. PID) :type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance of :class:`ElementProxy <hl7apy.core.ElementProxy>` :param value: the child value :type index: ``int`` :param index: the child position (e.g. 1) """ # just copy the first element of the ElementProxy (e.g. message.pid = message2.pid) if isinstance(value, ElementProxy): value = value[0].to_er7() name = name.upper() reference = None if name is None else self.element.find_child_reference(name) child_ref, child_name = (None, None) if reference is None else (reference['ref'], reference['name']) if isinstance(value, basestring): # if the value is a basestring, parse it child = self.element.parse_child(value, child_name=child_name, reference=child_ref) elif isinstance(value, Element): # it is already an instance of Element child = value elif isinstance(value, BaseDataType): child = self.create_element(name, False, reference) child.value = value else: raise ChildNotValid(value, child_name) if child.name != child_name: # e.g. message.pid = Segment('SPM') is forbidden raise ChildNotValid(value, child_name) child_to_remove = self.child_at_index(child_name, index) if child_to_remove is None: self.append(child) else: self.replace_child(child_to_remove, child) # a set has been called, change the temporary parent to be the actual one self.element.set_parent_to_traversal()
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:init_app; 3, parameters; 3, 4; 3, 5; 3, 6; 4, identifier:self; 5, identifier:app; 6, default_parameter; 6, 7; 6, 8; 7, identifier:config_prefix; 8, None; 9, block; 9, 10; 9, 12; 9, 13; 9, 28; 9, 29; 9, 39; 9, 40; 9, 59; 9, 60; 9, 61; 9, 68; 9, 87; 9, 100; 9, 101; 9, 116; 9, 117; 9, 131; 9, 132; 9, 146; 9, 147; 9, 148; 9, 254; 9, 255; 9, 256; 9, 270; 9, 311; 9, 320; 9, 361; 9, 362; 9, 370; 9, 380; 9, 381; 10, expression_statement; 10, 11; 11, comment; 12, comment; 13, if_statement; 13, 14; 13, 19; 14, comparison_operator:not; 14, 15; 14, 16; 15, string:'redis'; 16, attribute; 16, 17; 16, 18; 17, identifier:app; 18, identifier:extensions; 19, block; 19, 20; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 27; 22, subscript; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:app; 25, identifier:extensions; 26, string:'redis'; 27, dictionary; 28, comment; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:config_prefix; 34, assignment; 34, 35; 34, 36; 35, identifier:config_prefix; 36, boolean_operator:or; 36, 37; 36, 38; 37, identifier:config_prefix; 38, string:'REDIS'; 39, comment; 40, if_statement; 40, 41; 40, 48; 41, comparison_operator:in; 41, 42; 41, 43; 42, identifier:config_prefix; 43, subscript; 43, 44; 43, 47; 44, attribute; 44, 45; 44, 46; 45, identifier:app; 46, identifier:extensions; 47, string:'redis'; 48, block; 48, 49; 49, raise_statement; 49, 50; 50, call; 50, 51; 50, 52; 51, identifier:ValueError; 52, argument_list; 52, 53; 53, call; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, string:'Already registered config prefix {0!r}.'; 56, identifier:format; 57, argument_list; 57, 58; 58, identifier:config_prefix; 59, comment; 60, comment; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 64; 63, identifier:converters; 64, dictionary; 64, 65; 65, pair; 65, 66; 65, 67; 66, string:'port'; 67, identifier:int; 68, expression_statement; 68, 69; 69, assignment; 69, 70; 69, 71; 70, identifier:convert; 71, lambda; 71, 72; 71, 75; 72, lambda_parameters; 72, 73; 72, 74; 73, identifier:arg; 74, identifier:value; 75, parenthesized_expression; 75, 76; 76, conditional_expression:if; 76, 77; 76, 83; 76, 86; 77, call; 77, 78; 77, 81; 78, subscript; 78, 79; 78, 80; 79, identifier:converters; 80, identifier:arg; 81, argument_list; 81, 82; 82, identifier:value; 83, comparison_operator:in; 83, 84; 83, 85; 84, identifier:arg; 85, identifier:converters; 86, identifier:value; 87, expression_statement; 87, 88; 88, assignment; 88, 89; 88, 90; 89, identifier:key; 90, lambda; 90, 91; 90, 93; 91, lambda_parameters; 91, 92; 92, identifier:param; 93, call; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, string:'{0}_{1}'; 96, identifier:format; 97, argument_list; 97, 98; 97, 99; 98, identifier:config_prefix; 99, identifier:param; 100, comment; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 104; 103, identifier:klass; 104, call; 104, 105; 104, 110; 105, attribute; 105, 106; 105, 109; 106, attribute; 106, 107; 106, 108; 107, identifier:app; 108, identifier:config; 109, identifier:get; 110, argument_list; 110, 111; 110, 115; 111, call; 111, 112; 111, 113; 112, identifier:key; 113, argument_list; 113, 114; 114, string:'CLASS'; 115, identifier:RedisClass; 116, comment; 117, if_statement; 117, 118; 117, 123; 118, call; 118, 119; 118, 120; 119, identifier:isinstance; 120, argument_list; 120, 121; 120, 122; 121, identifier:klass; 122, identifier:string_types; 123, block; 123, 124; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:klass; 127, call; 127, 128; 127, 129; 128, identifier:import_string; 129, argument_list; 129, 130; 130, identifier:klass; 131, comment; 132, expression_statement; 132, 133; 133, assignment; 133, 134; 133, 135; 134, identifier:url; 135, call; 135, 136; 135, 141; 136, attribute; 136, 137; 136, 140; 137, attribute; 137, 138; 137, 139; 138, identifier:app; 139, identifier:config; 140, identifier:get; 141, argument_list; 141, 142; 142, call; 142, 143; 142, 144; 143, identifier:key; 144, argument_list; 144, 145; 145, string:'URL'; 146, comment; 147, comment; 148, if_statement; 148, 149; 148, 150; 149, identifier:url; 150, block; 150, 151; 150, 160; 150, 169; 150, 170; 150, 183; 150, 198; 150, 211; 150, 224; 150, 236; 151, expression_statement; 151, 152; 152, call; 152, 153; 152, 158; 153, attribute; 153, 154; 153, 157; 154, attribute; 154, 155; 154, 156; 155, identifier:urlparse; 156, identifier:uses_netloc; 157, identifier:append; 158, argument_list; 158, 159; 159, string:'redis'; 160, expression_statement; 160, 161; 161, assignment; 161, 162; 161, 163; 162, identifier:url; 163, call; 163, 164; 163, 167; 164, attribute; 164, 165; 164, 166; 165, identifier:urlparse; 166, identifier:urlparse; 167, argument_list; 167, 168; 168, identifier:url; 169, comment; 170, expression_statement; 170, 171; 171, assignment; 171, 172; 171, 180; 172, subscript; 172, 173; 172, 176; 173, attribute; 173, 174; 173, 175; 174, identifier:app; 175, identifier:config; 176, call; 176, 177; 176, 178; 177, identifier:key; 178, argument_list; 178, 179; 179, string:'HOST'; 180, attribute; 180, 181; 180, 182; 181, identifier:url; 182, identifier:hostname; 183, expression_statement; 183, 184; 184, assignment; 184, 185; 184, 193; 185, subscript; 185, 186; 185, 189; 186, attribute; 186, 187; 186, 188; 187, identifier:app; 188, identifier:config; 189, call; 189, 190; 189, 191; 190, identifier:key; 191, argument_list; 191, 192; 192, string:'PORT'; 193, boolean_operator:or; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:url; 196, identifier:port; 197, integer:6379; 198, expression_statement; 198, 199; 199, assignment; 199, 200; 199, 208; 200, subscript; 200, 201; 200, 204; 201, attribute; 201, 202; 201, 203; 202, identifier:app; 203, identifier:config; 204, call; 204, 205; 204, 206; 205, identifier:key; 206, argument_list; 206, 207; 207, string:'USER'; 208, attribute; 208, 209; 208, 210; 209, identifier:url; 210, identifier:username; 211, expression_statement; 211, 212; 212, assignment; 212, 213; 212, 221; 213, subscript; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:app; 216, identifier:config; 217, call; 217, 218; 217, 219; 218, identifier:key; 219, argument_list; 219, 220; 220, string:'PASSWORD'; 221, attribute; 221, 222; 221, 223; 222, identifier:url; 223, identifier:password; 224, expression_statement; 224, 225; 225, assignment; 225, 226; 225, 227; 226, identifier:db; 227, call; 227, 228; 227, 233; 228, attribute; 228, 229; 228, 232; 229, attribute; 229, 230; 229, 231; 230, identifier:url; 231, identifier:path; 232, identifier:replace; 233, argument_list; 233, 234; 233, 235; 234, string:'/'; 235, string:''; 236, expression_statement; 236, 237; 237, assignment; 237, 238; 237, 246; 238, subscript; 238, 239; 238, 242; 239, attribute; 239, 240; 239, 241; 240, identifier:app; 241, identifier:config; 242, call; 242, 243; 242, 244; 243, identifier:key; 244, argument_list; 244, 245; 245, string:'DB'; 246, conditional_expression:if; 246, 247; 246, 248; 246, 253; 247, identifier:db; 248, call; 248, 249; 248, 252; 249, attribute; 249, 250; 249, 251; 250, identifier:db; 251, identifier:isdigit; 252, argument_list; 253, None; 254, comment; 255, comment; 256, expression_statement; 256, 257; 257, assignment; 257, 258; 257, 259; 258, identifier:host; 259, call; 259, 260; 259, 265; 260, attribute; 260, 261; 260, 264; 261, attribute; 261, 262; 261, 263; 262, identifier:app; 263, identifier:config; 264, identifier:get; 265, argument_list; 265, 266; 266, call; 266, 267; 266, 268; 267, identifier:key; 268, argument_list; 268, 269; 269, string:'HOST'; 270, if_statement; 270, 271; 270, 287; 271, boolean_operator:and; 271, 272; 271, 273; 272, identifier:host; 273, parenthesized_expression; 273, 274; 274, boolean_operator:or; 274, 275; 274, 281; 275, call; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:host; 278, identifier:startswith; 279, argument_list; 279, 280; 280, string:'file://'; 281, call; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:host; 284, identifier:startswith; 285, argument_list; 285, 286; 286, string:'/'; 287, block; 287, 288; 287, 300; 288, expression_statement; 288, 289; 289, call; 289, 290; 289, 295; 290, attribute; 290, 291; 290, 294; 291, attribute; 291, 292; 291, 293; 292, identifier:app; 293, identifier:config; 294, identifier:pop; 295, argument_list; 295, 296; 296, call; 296, 297; 296, 298; 297, identifier:key; 298, argument_list; 298, 299; 299, string:'HOST'; 300, expression_statement; 300, 301; 301, assignment; 301, 302; 301, 310; 302, subscript; 302, 303; 302, 306; 303, attribute; 303, 304; 303, 305; 304, identifier:app; 305, identifier:config; 306, call; 306, 307; 306, 308; 307, identifier:key; 308, argument_list; 308, 309; 309, string:'UNIX_SOCKET_PATH'; 310, identifier:host; 311, expression_statement; 311, 312; 312, assignment; 312, 313; 312, 314; 313, identifier:args; 314, call; 314, 315; 314, 318; 315, attribute; 315, 316; 315, 317; 316, identifier:self; 317, identifier:_build_connection_args; 318, argument_list; 318, 319; 319, identifier:klass; 320, expression_statement; 320, 321; 321, assignment; 321, 322; 321, 323; 322, identifier:kwargs; 323, call; 323, 324; 323, 325; 324, identifier:dict; 325, argument_list; 325, 326; 326, list_comprehension; 326, 327; 326, 345; 326, 348; 327, tuple; 327, 328; 327, 329; 328, identifier:arg; 329, call; 329, 330; 329, 331; 330, identifier:convert; 331, argument_list; 331, 332; 331, 333; 332, identifier:arg; 333, subscript; 333, 334; 333, 337; 334, attribute; 334, 335; 334, 336; 335, identifier:app; 336, identifier:config; 337, call; 337, 338; 337, 339; 338, identifier:key; 339, argument_list; 339, 340; 340, call; 340, 341; 340, 344; 341, attribute; 341, 342; 341, 343; 342, identifier:arg; 343, identifier:upper; 344, argument_list; 345, for_in_clause; 345, 346; 345, 347; 346, identifier:arg; 347, identifier:args; 348, if_clause; 348, 349; 349, comparison_operator:in; 349, 350; 349, 358; 350, call; 350, 351; 350, 352; 351, identifier:key; 352, argument_list; 352, 353; 353, call; 353, 354; 353, 357; 354, attribute; 354, 355; 354, 356; 355, identifier:arg; 356, identifier:upper; 357, argument_list; 358, attribute; 358, 359; 358, 360; 359, identifier:app; 360, identifier:config; 361, comment; 362, expression_statement; 362, 363; 363, assignment; 363, 364; 363, 365; 364, identifier:connection; 365, call; 365, 366; 365, 367; 366, identifier:klass; 367, argument_list; 367, 368; 368, dictionary_splat; 368, 369; 369, identifier:kwargs; 370, expression_statement; 370, 371; 371, assignment; 371, 372; 371, 379; 372, subscript; 372, 373; 372, 378; 373, subscript; 373, 374; 373, 377; 374, attribute; 374, 375; 374, 376; 375, identifier:app; 376, identifier:extensions; 377, string:'redis'; 378, identifier:config_prefix; 379, identifier:connection; 380, comment; 381, expression_statement; 381, 382; 382, call; 382, 383; 382, 386; 383, attribute; 383, 384; 383, 385; 384, identifier:self; 385, identifier:_include_public_methods; 386, argument_list; 386, 387; 387, identifier:connection
def init_app(self, app, config_prefix=None): """ Actual method to read redis settings from app configuration, initialize Redis connection and copy all public connection methods to current instance. :param app: :class:`flask.Flask` application instance. :param config_prefix: Config prefix to use. By default: ``REDIS`` """ # Put redis to application extensions if 'redis' not in app.extensions: app.extensions['redis'] = {} # Which config prefix to use, custom or default one? self.config_prefix = config_prefix = config_prefix or 'REDIS' # No way to do registration two times if config_prefix in app.extensions['redis']: raise ValueError('Already registered config prefix {0!r}.'. format(config_prefix)) # Start reading configuration, define converters to use and key func # to prepend config prefix to key value converters = {'port': int} convert = lambda arg, value: (converters[arg](value) if arg in converters else value) key = lambda param: '{0}_{1}'.format(config_prefix, param) # Which redis connection class to use? klass = app.config.get(key('CLASS'), RedisClass) # Import connection class if it stil path notation if isinstance(klass, string_types): klass = import_string(klass) # Should we use URL configuration url = app.config.get(key('URL')) # If should, parse URL and store values to application config to later # reuse if necessary if url: urlparse.uses_netloc.append('redis') url = urlparse.urlparse(url) # URL could contains host, port, user, password and db values app.config[key('HOST')] = url.hostname app.config[key('PORT')] = url.port or 6379 app.config[key('USER')] = url.username app.config[key('PASSWORD')] = url.password db = url.path.replace('/', '') app.config[key('DB')] = db if db.isdigit() else None # Host is not a mandatory key if you want to use connection pool. But # when present and starts with file:// or / use it as unix socket path host = app.config.get(key('HOST')) if host and (host.startswith('file://') or host.startswith('/')): app.config.pop(key('HOST')) app.config[key('UNIX_SOCKET_PATH')] = host args = self._build_connection_args(klass) kwargs = dict([(arg, convert(arg, app.config[key(arg.upper())])) for arg in args if key(arg.upper()) in app.config]) # Initialize connection and store it to extensions connection = klass(**kwargs) app.extensions['redis'][config_prefix] = connection # Include public methods to current instance self._include_public_methods(connection)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 1, 6; 1, 7; 1, 8; 2, function_name:__setup_native_run; 3, parameters; 3, 4; 4, identifier:self; 5, comment; 6, comment; 7, comment; 8, block; 8, 9; 8, 16; 8, 17; 8, 32; 8, 62; 8, 75; 8, 76; 8, 77; 8, 78; 8, 90; 8, 91; 8, 104; 8, 105; 8, 106; 8, 130; 8, 131; 8, 160; 8, 173; 8, 175; 8, 228; 8, 229; 8, 230; 8, 242; 8, 248; 8, 316; 8, 317; 8, 371; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 14; 11, attribute; 11, 12; 11, 13; 12, identifier:self; 13, identifier:vol_opts; 14, list:['z']; 14, 15; 15, string:'z'; 16, comment; 17, expression_statement; 17, 18; 18, call; 18, 19; 18, 22; 19, attribute; 19, 20; 19, 21; 20, identifier:self; 21, identifier:add_env; 22, argument_list; 22, 23; 22, 24; 23, string:'SCUBAINIT_UMASK'; 24, call; 24, 25; 24, 28; 25, attribute; 25, 26; 25, 27; 26, string:'{:04o}'; 27, identifier:format; 28, argument_list; 28, 29; 29, call; 29, 30; 29, 31; 30, identifier:get_umask; 31, argument_list; 32, if_statement; 32, 33; 32, 37; 33, not_operator; 33, 34; 34, attribute; 34, 35; 34, 36; 35, identifier:self; 36, identifier:as_root; 37, block; 37, 38; 37, 50; 38, expression_statement; 38, 39; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:self; 42, identifier:add_env; 43, argument_list; 43, 44; 43, 45; 44, string:'SCUBAINIT_UID'; 45, call; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:os; 48, identifier:getuid; 49, argument_list; 50, expression_statement; 50, 51; 51, call; 51, 52; 51, 55; 52, attribute; 52, 53; 52, 54; 53, identifier:self; 54, identifier:add_env; 55, argument_list; 55, 56; 55, 57; 56, string:'SCUBAINIT_GID'; 57, call; 57, 58; 57, 61; 58, attribute; 58, 59; 58, 60; 59, identifier:os; 60, identifier:getgid; 61, argument_list; 62, if_statement; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:self; 65, identifier:verbose; 66, block; 66, 67; 67, expression_statement; 67, 68; 68, call; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:self; 71, identifier:add_env; 72, argument_list; 72, 73; 72, 74; 73, string:'SCUBAINIT_VERBOSE'; 74, integer:1; 75, comment; 76, comment; 77, comment; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:scubainit_cpath; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:self; 84, identifier:copy_scubadir_file; 85, argument_list; 85, 86; 85, 87; 86, string:'scubainit'; 87, attribute; 87, 88; 87, 89; 88, identifier:self; 89, identifier:scubainit_path; 90, comment; 91, for_statement; 91, 92; 91, 93; 91, 96; 92, identifier:name; 93, tuple; 93, 94; 93, 95; 94, string:'root'; 95, string:'user'; 96, block; 96, 97; 97, expression_statement; 97, 98; 98, call; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, identifier:self; 101, identifier:__generate_hook_script; 102, argument_list; 102, 103; 103, identifier:name; 104, comment; 105, comment; 106, if_statement; 106, 107; 106, 122; 107, boolean_operator:and; 107, 108; 107, 115; 108, call; 108, 109; 108, 114; 109, attribute; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:sys; 112, identifier:stdout; 113, identifier:isatty; 114, argument_list; 115, call; 115, 116; 115, 121; 116, attribute; 116, 117; 116, 120; 117, attribute; 117, 118; 117, 119; 118, identifier:sys; 119, identifier:stdin; 120, identifier:isatty; 121, argument_list; 122, block; 122, 123; 123, expression_statement; 123, 124; 124, call; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:self; 127, identifier:add_option; 128, argument_list; 128, 129; 129, string:'--tty'; 130, comment; 131, try_statement; 131, 132; 131, 146; 132, block; 132, 133; 133, expression_statement; 133, 134; 134, assignment; 134, 135; 134, 136; 135, identifier:context; 136, call; 136, 137; 136, 142; 137, attribute; 137, 138; 137, 141; 138, attribute; 138, 139; 138, 140; 139, identifier:self; 140, identifier:config; 141, identifier:process_command; 142, argument_list; 142, 143; 143, attribute; 143, 144; 143, 145; 144, identifier:self; 145, identifier:user_command; 146, except_clause; 146, 147; 146, 151; 147, as_pattern; 147, 148; 147, 149; 148, identifier:ConfigError; 149, as_pattern_target; 149, 150; 150, identifier:cfgerr; 151, block; 151, 152; 152, raise_statement; 152, 153; 153, call; 153, 154; 153, 155; 154, identifier:ScubaError; 155, argument_list; 155, 156; 156, call; 156, 157; 156, 158; 157, identifier:str; 158, argument_list; 158, 159; 159, identifier:cfgerr; 160, if_statement; 160, 161; 160, 164; 161, attribute; 161, 162; 161, 163; 162, identifier:self; 163, identifier:image_override; 164, block; 164, 165; 165, expression_statement; 165, 166; 166, assignment; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:context; 169, identifier:image; 170, attribute; 170, 171; 170, 172; 171, identifier:self; 172, identifier:image_override; 173, expression_statement; 173, 174; 174, string:''' Normally, if the user provides no command to "docker run", the image's default CMD is run. Because we set the entrypiont, scuba must emulate the default behavior itself. '''; 175, if_statement; 175, 176; 175, 180; 175, 181; 176, not_operator; 176, 177; 177, attribute; 177, 178; 177, 179; 178, identifier:context; 179, identifier:script; 180, comment; 181, block; 181, 182; 181, 187; 181, 196; 181, 205; 181, 218; 182, expression_statement; 182, 183; 183, call; 183, 184; 183, 185; 184, identifier:verbose_msg; 185, argument_list; 185, 186; 186, string:'No user command; getting command from image'; 187, expression_statement; 187, 188; 188, assignment; 188, 189; 188, 190; 189, identifier:default_cmd; 190, call; 190, 191; 190, 192; 191, identifier:get_image_command; 192, argument_list; 192, 193; 193, attribute; 193, 194; 193, 195; 194, identifier:context; 195, identifier:image; 196, if_statement; 196, 197; 196, 199; 197, not_operator; 197, 198; 198, identifier:default_cmd; 199, block; 199, 200; 200, raise_statement; 200, 201; 201, call; 201, 202; 201, 203; 202, identifier:ScubaError; 203, argument_list; 203, 204; 204, string:'No command given and no image-specified command'; 205, expression_statement; 205, 206; 206, call; 206, 207; 206, 208; 207, identifier:verbose_msg; 208, argument_list; 208, 209; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, string:'{} Cmd: "{}"'; 212, identifier:format; 213, argument_list; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:context; 216, identifier:image; 217, identifier:default_cmd; 218, expression_statement; 218, 219; 219, assignment; 219, 220; 219, 223; 220, attribute; 220, 221; 220, 222; 221, identifier:context; 222, identifier:script; 223, list:[shell_quote_cmd(default_cmd)]; 223, 224; 224, call; 224, 225; 224, 226; 225, identifier:shell_quote_cmd; 226, argument_list; 226, 227; 227, identifier:default_cmd; 228, comment; 229, comment; 230, expression_statement; 230, 231; 231, call; 231, 232; 231, 235; 232, attribute; 232, 233; 232, 234; 233, identifier:self; 234, identifier:add_option; 235, argument_list; 235, 236; 236, call; 236, 237; 236, 240; 237, attribute; 237, 238; 237, 239; 238, string:'--entrypoint={}'; 239, identifier:format; 240, argument_list; 240, 241; 241, identifier:scubainit_cpath; 242, expression_statement; 242, 243; 243, assignment; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:self; 246, identifier:docker_cmd; 247, list:[]; 248, if_statement; 248, 249; 248, 254; 248, 255; 248, 272; 248, 296; 249, comparison_operator:is; 249, 250; 249, 253; 250, attribute; 250, 251; 250, 252; 251, identifier:self; 252, identifier:entrypoint_override; 253, None; 254, comment; 255, block; 255, 256; 256, if_statement; 256, 257; 256, 262; 257, comparison_operator:!=; 257, 258; 257, 261; 258, attribute; 258, 259; 258, 260; 259, identifier:self; 260, identifier:entrypoint_override; 261, string:''; 262, block; 262, 263; 263, expression_statement; 263, 264; 264, assignment; 264, 265; 264, 268; 265, attribute; 265, 266; 265, 267; 266, identifier:self; 267, identifier:docker_cmd; 268, list:[self.entrypoint_override]; 268, 269; 269, attribute; 269, 270; 269, 271; 270, identifier:self; 271, identifier:entrypoint_override; 272, elif_clause; 272, 273; 272, 278; 272, 279; 273, comparison_operator:is; 273, 274; 273, 277; 274, attribute; 274, 275; 274, 276; 275, identifier:context; 276, identifier:entrypoint; 277, None; 278, comment; 279, block; 279, 280; 280, if_statement; 280, 281; 280, 286; 281, comparison_operator:!=; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:context; 284, identifier:entrypoint; 285, string:''; 286, block; 286, 287; 287, expression_statement; 287, 288; 288, assignment; 288, 289; 288, 292; 289, attribute; 289, 290; 289, 291; 290, identifier:self; 291, identifier:docker_cmd; 292, list:[context.entrypoint]; 292, 293; 293, attribute; 293, 294; 293, 295; 294, identifier:context; 295, identifier:entrypoint; 296, else_clause; 296, 297; 297, block; 297, 298; 297, 307; 298, expression_statement; 298, 299; 299, assignment; 299, 300; 299, 301; 300, identifier:ep; 301, call; 301, 302; 301, 303; 302, identifier:get_image_entrypoint; 303, argument_list; 303, 304; 304, attribute; 304, 305; 304, 306; 305, identifier:context; 306, identifier:image; 307, if_statement; 307, 308; 307, 309; 308, identifier:ep; 309, block; 309, 310; 310, expression_statement; 310, 311; 311, assignment; 311, 312; 311, 315; 312, attribute; 312, 313; 312, 314; 313, identifier:self; 314, identifier:docker_cmd; 315, identifier:ep; 316, comment; 317, with_statement; 317, 318; 317, 330; 318, with_clause; 318, 319; 319, with_item; 319, 320; 320, as_pattern; 320, 321; 320, 328; 321, call; 321, 322; 321, 325; 322, attribute; 322, 323; 322, 324; 323, identifier:self; 324, identifier:open_scubadir_file; 325, argument_list; 325, 326; 325, 327; 326, string:'command.sh'; 327, string:'wt'; 328, as_pattern_target; 328, 329; 329, identifier:f; 330, block; 330, 331; 330, 341; 330, 347; 330, 353; 330, 359; 331, expression_statement; 331, 332; 332, augmented_assignment:+=; 332, 333; 332, 336; 333, attribute; 333, 334; 333, 335; 334, identifier:self; 335, identifier:docker_cmd; 336, list:['/bin/sh', f.container_path]; 336, 337; 336, 338; 337, string:'/bin/sh'; 338, attribute; 338, 339; 338, 340; 339, identifier:f; 340, identifier:container_path; 341, expression_statement; 341, 342; 342, call; 342, 343; 342, 344; 343, identifier:writeln; 344, argument_list; 344, 345; 344, 346; 345, identifier:f; 346, string:'#!/bin/sh'; 347, expression_statement; 347, 348; 348, call; 348, 349; 348, 350; 349, identifier:writeln; 350, argument_list; 350, 351; 350, 352; 351, identifier:f; 352, string:'# Auto-generated from scuba'; 353, expression_statement; 353, 354; 354, call; 354, 355; 354, 356; 355, identifier:writeln; 356, argument_list; 356, 357; 356, 358; 357, identifier:f; 358, string:'set -e'; 359, for_statement; 359, 360; 359, 361; 359, 364; 360, identifier:cmd; 361, attribute; 361, 362; 361, 363; 362, identifier:context; 363, identifier:script; 364, block; 364, 365; 365, expression_statement; 365, 366; 366, call; 366, 367; 366, 368; 367, identifier:writeln; 368, argument_list; 368, 369; 368, 370; 369, identifier:f; 370, identifier:cmd; 371, expression_statement; 371, 372; 372, assignment; 372, 373; 372, 376; 373, attribute; 373, 374; 373, 375; 374, identifier:self; 375, identifier:context; 376, identifier:context
def __setup_native_run(self): # These options are appended to mounted volume arguments # NOTE: This tells Docker to re-label the directory for compatibility # with SELinux. See `man docker-run` for more information. self.vol_opts = ['z'] # Pass variables to scubainit self.add_env('SCUBAINIT_UMASK', '{:04o}'.format(get_umask())) if not self.as_root: self.add_env('SCUBAINIT_UID', os.getuid()) self.add_env('SCUBAINIT_GID', os.getgid()) if self.verbose: self.add_env('SCUBAINIT_VERBOSE', 1) # Copy scubainit into the container # We make a copy because Docker 1.13 gets pissed if we try to re-label # /usr, and Fedora 28 gives an AVC denial. scubainit_cpath = self.copy_scubadir_file('scubainit', self.scubainit_path) # Hooks for name in ('root', 'user', ): self.__generate_hook_script(name) # allocate TTY if scuba's output is going to a terminal # and stdin is not redirected if sys.stdout.isatty() and sys.stdin.isatty(): self.add_option('--tty') # Process any aliases try: context = self.config.process_command(self.user_command) except ConfigError as cfgerr: raise ScubaError(str(cfgerr)) if self.image_override: context.image = self.image_override ''' Normally, if the user provides no command to "docker run", the image's default CMD is run. Because we set the entrypiont, scuba must emulate the default behavior itself. ''' if not context.script: # No user-provided command; we want to run the image's default command verbose_msg('No user command; getting command from image') default_cmd = get_image_command(context.image) if not default_cmd: raise ScubaError('No command given and no image-specified command') verbose_msg('{} Cmd: "{}"'.format(context.image, default_cmd)) context.script = [shell_quote_cmd(default_cmd)] # Make scubainit the real entrypoint, and use the defined entrypoint as # the docker command (if it exists) self.add_option('--entrypoint={}'.format(scubainit_cpath)) self.docker_cmd = [] if self.entrypoint_override is not None: # --entrypoint takes precedence if self.entrypoint_override != '': self.docker_cmd = [self.entrypoint_override] elif context.entrypoint is not None: # then .scuba.yml if context.entrypoint != '': self.docker_cmd = [context.entrypoint] else: ep = get_image_entrypoint(context.image) if ep: self.docker_cmd = ep # The user command is executed via a generated shell script with self.open_scubadir_file('command.sh', 'wt') as f: self.docker_cmd += ['/bin/sh', f.container_path] writeln(f, '#!/bin/sh') writeln(f, '# Auto-generated from scuba') writeln(f, 'set -e') for cmd in context.script: writeln(f, cmd) self.context = context
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 1, 18; 2, function_name:sort; 3, parameters; 3, 4; 4, typed_parameter; 4, 5; 4, 6; 5, identifier:records; 6, type; 6, 7; 7, generic_type; 7, 8; 7, 9; 8, identifier:Sequence; 9, type_parameter; 9, 10; 10, type; 10, 11; 11, identifier:Record; 12, type; 12, 13; 13, generic_type; 13, 14; 13, 15; 14, identifier:List; 15, type_parameter; 15, 16; 16, type; 16, 17; 17, identifier:Record; 18, block; 18, 19; 18, 21; 19, expression_statement; 19, 20; 20, string:"Sort records into a canonical order, suitable for comparison."; 21, return_statement; 21, 22; 22, call; 22, 23; 22, 24; 23, identifier:sorted; 24, argument_list; 24, 25; 24, 26; 25, identifier:records; 26, keyword_argument; 26, 27; 26, 28; 27, identifier:key; 28, identifier:_record_key
def sort(records: Sequence[Record]) -> List[Record]: "Sort records into a canonical order, suitable for comparison." return sorted(records, key=_record_key)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 11; 2, function_name:_issubclass_Mapping_covariant; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 3, 9; 3, 10; 4, identifier:subclass; 5, identifier:superclass; 6, identifier:bound_Generic; 7, identifier:bound_typevars; 8, identifier:bound_typevars_readonly; 9, identifier:follow_fwd_refs; 10, identifier:_recursion_check; 11, block; 11, 12; 11, 14; 11, 180; 12, expression_statement; 12, 13; 13, comment; 14, if_statement; 14, 15; 14, 19; 15, call; 15, 16; 15, 17; 16, identifier:is_Generic; 17, argument_list; 17, 18; 18, identifier:subclass; 19, block; 19, 20; 19, 47; 19, 92; 19, 140; 19, 159; 19, 178; 20, if_statement; 20, 21; 20, 35; 21, boolean_operator:or; 21, 22; 21, 27; 22, comparison_operator:is; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:subclass; 25, identifier:__origin__; 26, None; 27, not_operator; 27, 28; 28, call; 28, 29; 28, 30; 29, identifier:issubclass; 30, argument_list; 30, 31; 30, 34; 31, attribute; 31, 32; 31, 33; 32, identifier:subclass; 33, identifier:__origin__; 34, identifier:Mapping; 35, block; 35, 36; 36, return_statement; 36, 37; 37, call; 37, 38; 37, 39; 38, identifier:_issubclass_Generic; 39, argument_list; 39, 40; 39, 41; 39, 42; 39, 43; 39, 44; 39, 45; 39, 46; 40, identifier:subclass; 41, identifier:superclass; 42, identifier:bound_Generic; 43, identifier:bound_typevars; 44, identifier:bound_typevars_readonly; 45, identifier:follow_fwd_refs; 46, identifier:_recursion_check; 47, if_statement; 47, 48; 47, 53; 47, 84; 48, comparison_operator:is; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:superclass; 51, identifier:__args__; 52, None; 53, block; 53, 54; 53, 70; 53, 78; 54, if_statement; 54, 55; 54, 59; 55, not_operator; 55, 56; 56, attribute; 56, 57; 56, 58; 57, identifier:pytypes; 58, identifier:check_unbound_types; 59, block; 59, 60; 60, raise_statement; 60, 61; 61, call; 61, 62; 61, 63; 62, identifier:TypeError; 63, argument_list; 63, 64; 64, binary_operator:+; 64, 65; 64, 66; 65, string:"Attempted to check unbound mapping type(superclass): "; 66, call; 66, 67; 66, 68; 67, identifier:str; 68, argument_list; 68, 69; 69, identifier:superclass; 70, if_statement; 70, 71; 70, 74; 70, 75; 71, attribute; 71, 72; 71, 73; 72, identifier:pytypes; 73, identifier:strict_unknown_check; 74, comment; 75, block; 75, 76; 76, return_statement; 76, 77; 77, False; 78, expression_statement; 78, 79; 79, assignment; 79, 80; 79, 81; 80, identifier:super_args; 81, tuple; 81, 82; 81, 83; 82, identifier:Any; 83, identifier:Any; 84, else_clause; 84, 85; 85, block; 85, 86; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:super_args; 89, attribute; 89, 90; 89, 91; 90, identifier:superclass; 91, identifier:__args__; 92, if_statement; 92, 93; 92, 98; 92, 132; 93, comparison_operator:is; 93, 94; 93, 97; 94, attribute; 94, 95; 94, 96; 95, identifier:subclass; 96, identifier:__args__; 97, None; 98, block; 98, 99; 98, 115; 98, 126; 99, if_statement; 99, 100; 99, 104; 100, not_operator; 100, 101; 101, attribute; 101, 102; 101, 103; 102, identifier:pytypes; 103, identifier:check_unbound_types; 104, block; 104, 105; 105, raise_statement; 105, 106; 106, call; 106, 107; 106, 108; 107, identifier:TypeError; 108, argument_list; 108, 109; 109, binary_operator:+; 109, 110; 109, 111; 110, string:"Attempted to check unbound mapping type(subclass): "; 111, call; 111, 112; 111, 113; 112, identifier:str; 113, argument_list; 113, 114; 114, identifier:subclass; 115, if_statement; 115, 116; 115, 119; 115, 120; 115, 121; 115, 122; 115, 123; 116, attribute; 116, 117; 116, 118; 117, identifier:pytypes; 118, identifier:strict_unknown_check; 119, comment; 120, comment; 121, comment; 122, comment; 123, block; 123, 124; 124, return_statement; 124, 125; 125, False; 126, expression_statement; 126, 127; 127, assignment; 127, 128; 127, 129; 128, identifier:sub_args; 129, tuple; 129, 130; 129, 131; 130, identifier:Any; 131, identifier:Any; 132, else_clause; 132, 133; 133, block; 133, 134; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:sub_args; 137, attribute; 137, 138; 137, 139; 138, identifier:subclass; 139, identifier:__args__; 140, if_statement; 140, 141; 140, 156; 141, not_operator; 141, 142; 142, call; 142, 143; 142, 144; 143, identifier:_issubclass; 144, argument_list; 144, 145; 144, 148; 144, 151; 144, 152; 144, 153; 144, 154; 144, 155; 145, subscript; 145, 146; 145, 147; 146, identifier:sub_args; 147, integer:0; 148, subscript; 148, 149; 148, 150; 149, identifier:super_args; 150, integer:0; 151, identifier:bound_Generic; 152, identifier:bound_typevars; 153, identifier:bound_typevars_readonly; 154, identifier:follow_fwd_refs; 155, identifier:_recursion_check; 156, block; 156, 157; 157, return_statement; 157, 158; 158, False; 159, if_statement; 159, 160; 159, 175; 160, not_operator; 160, 161; 161, call; 161, 162; 161, 163; 162, identifier:_issubclass; 163, argument_list; 163, 164; 163, 167; 163, 170; 163, 171; 163, 172; 163, 173; 163, 174; 164, subscript; 164, 165; 164, 166; 165, identifier:sub_args; 166, integer:1; 167, subscript; 167, 168; 167, 169; 168, identifier:super_args; 169, integer:1; 170, identifier:bound_Generic; 171, identifier:bound_typevars; 172, identifier:bound_typevars_readonly; 173, identifier:follow_fwd_refs; 174, identifier:_recursion_check; 175, block; 175, 176; 176, return_statement; 176, 177; 177, False; 178, return_statement; 178, 179; 179, True; 180, return_statement; 180, 181; 181, call; 181, 182; 181, 183; 182, identifier:issubclass; 183, argument_list; 183, 184; 183, 185; 184, identifier:subclass; 185, identifier:superclass
def _issubclass_Mapping_covariant(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Helper for _issubclass, a.k.a pytypes.issubtype. This subclass-check treats Mapping-values as covariant. """ if is_Generic(subclass): if subclass.__origin__ is None or not issubclass(subclass.__origin__, Mapping): return _issubclass_Generic(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) if superclass.__args__ is None: if not pytypes.check_unbound_types: raise TypeError("Attempted to check unbound mapping type(superclass): "+ str(superclass)) if pytypes.strict_unknown_check: # Nothing is subtype of unknown type return False super_args = (Any, Any) else: super_args = superclass.__args__ if subclass.__args__ is None: if not pytypes.check_unbound_types: raise TypeError("Attempted to check unbound mapping type(subclass): "+ str(subclass)) if pytypes.strict_unknown_check: # Nothing can subclass unknown type # For value type it would be okay if superclass had Any as value type, # as unknown type is subtype of Any. However, since key type is invariant # and also unknown, it cannot pass. return False sub_args = (Any, Any) else: sub_args = subclass.__args__ if not _issubclass(sub_args[0], super_args[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): return False if not _issubclass(sub_args[1], super_args[1], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): return False return True return issubclass(subclass, superclass)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 21; 2, function_name:_isinstance; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 3, 12; 3, 15; 3, 18; 4, identifier:obj; 5, identifier:cls; 6, default_parameter; 6, 7; 6, 8; 7, identifier:bound_Generic; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:bound_typevars; 11, None; 12, default_parameter; 12, 13; 12, 14; 13, identifier:bound_typevars_readonly; 14, False; 15, default_parameter; 15, 16; 15, 17; 16, identifier:follow_fwd_refs; 17, True; 18, default_parameter; 18, 19; 18, 20; 19, identifier:_recursion_check; 20, None; 21, block; 21, 22; 21, 24; 21, 33; 21, 34; 21, 91; 21, 108; 22, expression_statement; 22, 23; 23, comment; 24, if_statement; 24, 25; 24, 28; 25, comparison_operator:is; 25, 26; 25, 27; 26, identifier:bound_typevars; 27, None; 28, block; 28, 29; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:bound_typevars; 32, dictionary; 33, comment; 34, if_statement; 34, 35; 34, 47; 35, boolean_operator:and; 35, 36; 35, 40; 36, call; 36, 37; 36, 38; 37, identifier:is_Generic; 38, argument_list; 38, 39; 39, identifier:cls; 40, comparison_operator:is; 40, 41; 40, 44; 41, attribute; 41, 42; 41, 43; 42, identifier:cls; 43, identifier:__origin__; 44, attribute; 44, 45; 44, 46; 45, identifier:typing; 46, identifier:Iterable; 47, block; 47, 48; 47, 57; 47, 64; 48, if_statement; 48, 49; 48, 54; 49, not_operator; 49, 50; 50, call; 50, 51; 50, 52; 51, identifier:is_iterable; 52, argument_list; 52, 53; 53, identifier:obj; 54, block; 54, 55; 55, return_statement; 55, 56; 56, False; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:itp; 60, call; 60, 61; 60, 62; 61, identifier:get_iterable_itemtype; 62, argument_list; 62, 63; 63, identifier:obj; 64, if_statement; 64, 65; 64, 68; 64, 74; 65, comparison_operator:is; 65, 66; 65, 67; 66, identifier:itp; 67, None; 68, block; 68, 69; 69, return_statement; 69, 70; 70, not_operator; 70, 71; 71, attribute; 71, 72; 71, 73; 72, identifier:pytypes; 73, identifier:check_iterables; 74, else_clause; 74, 75; 75, block; 75, 76; 76, return_statement; 76, 77; 77, call; 77, 78; 77, 79; 78, identifier:_issubclass; 79, argument_list; 79, 80; 79, 81; 79, 86; 79, 87; 79, 88; 79, 89; 79, 90; 80, identifier:itp; 81, subscript; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:cls; 84, identifier:__args__; 85, integer:0; 86, identifier:bound_Generic; 87, identifier:bound_typevars; 88, identifier:bound_typevars_readonly; 89, identifier:follow_fwd_refs; 90, identifier:_recursion_check; 91, if_statement; 91, 92; 91, 96; 92, call; 92, 93; 92, 94; 93, identifier:is_Callable; 94, argument_list; 94, 95; 95, identifier:cls; 96, block; 96, 97; 97, return_statement; 97, 98; 98, call; 98, 99; 98, 100; 99, identifier:_isinstance_Callable; 100, argument_list; 100, 101; 100, 102; 100, 103; 100, 104; 100, 105; 100, 106; 100, 107; 101, identifier:obj; 102, identifier:cls; 103, identifier:bound_Generic; 104, identifier:bound_typevars; 105, identifier:bound_typevars_readonly; 106, identifier:follow_fwd_refs; 107, identifier:_recursion_check; 108, return_statement; 108, 109; 109, call; 109, 110; 109, 111; 110, identifier:_issubclass; 111, argument_list; 111, 112; 111, 116; 111, 117; 111, 118; 111, 119; 111, 120; 111, 121; 112, call; 112, 113; 112, 114; 113, identifier:deep_type; 114, argument_list; 114, 115; 115, identifier:obj; 116, identifier:cls; 117, identifier:bound_Generic; 118, identifier:bound_typevars; 119, identifier:bound_typevars_readonly; 120, identifier:follow_fwd_refs; 121, identifier:_recursion_check
def _isinstance(obj, cls, bound_Generic=None, bound_typevars=None, bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None): """Access this via ``pytypes.is_of_type``. Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module. obj : Any The object to check for being an instance of ``cls``. cls : type The type to check for ``obj`` being an instance of. bound_Generic : Optional[Generic] A type object holding values for unbound typevars occurring in ``cls``. Default: None If ``cls`` contains unbound ``TypeVar``s and ``bound_Generic`` is provided, this function attempts to retrieve corresponding values for the unbound ``TypeVar``s from ``bound_Generic``. In collision case with ``bound_typevars`` the value from ``bound_Generic`` if preferred. bound_typevars : Optional[Dict[typing.TypeVar, type]] A dictionary holding values for unbound typevars occurring in ``cls``. Default: {} Depending on ``bound_typevars_readonly`` pytypes can also bind values to typevars as needed. This is done by inserting according mappings into this dictionary. This can e.g. be useful to infer values for ``TypeVar``s or to consistently check a set of ``TypeVar``s across multiple calls, e.g. when checking all arguments of a function call. In collision case with ``bound_Generic`` the value from ``bound_Generic`` if preferred. bound_typevars_readonly : bool Defines if pytypes is allowed to write into the ``bound_typevars`` dictionary. Default: True If set to False, pytypes cannot assign values to ``TypeVar``s, but only checks regarding values already present in ``bound_typevars`` or ``bound_Generic``. follow_fwd_refs : bool Defines if ``ForwardRef``s should be explored. Default: True If this is set to ``False`` and a ``ForwardRef`` is encountered, pytypes aborts the check raising a ForwardRefError. _recursion_check : Optional[Dict[type, Set[type]]] Internally used for recursion checks. Default: None If ``Union``s and ``ForwardRef``s occur in the same type, recursions can occur. As soon as a ``ForwardRef`` is encountered, pytypes automatically creates this dictionary and continues in recursion-proof manner. """ if bound_typevars is None: bound_typevars = {} # Special treatment if cls is Iterable[...] if is_Generic(cls) and cls.__origin__ is typing.Iterable: if not is_iterable(obj): return False itp = get_iterable_itemtype(obj) if itp is None: return not pytypes.check_iterables else: return _issubclass(itp, cls.__args__[0], bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) if is_Callable(cls): return _isinstance_Callable(obj, cls, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) return _issubclass(deep_type(obj), cls, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:typelogged_module; 3, parameters; 3, 4; 4, identifier:md; 5, block; 5, 6; 5, 8; 5, 16; 5, 70; 5, 76; 5, 105; 5, 111; 5, 134; 5, 135; 5, 136; 5, 137; 5, 138; 5, 148; 5, 203; 5, 228; 6, expression_statement; 6, 7; 7, comment; 8, if_statement; 8, 9; 8, 13; 9, not_operator; 9, 10; 10, attribute; 10, 11; 10, 12; 11, identifier:pytypes; 12, identifier:typelogging_enabled; 13, block; 13, 14; 14, return_statement; 14, 15; 15, identifier:md; 16, if_statement; 16, 17; 16, 22; 17, call; 17, 18; 17, 19; 18, identifier:isinstance; 19, argument_list; 19, 20; 19, 21; 20, identifier:md; 21, identifier:str; 22, block; 22, 23; 23, if_statement; 23, 24; 23, 29; 23, 45; 24, comparison_operator:in; 24, 25; 24, 26; 25, identifier:md; 26, attribute; 26, 27; 26, 28; 27, identifier:sys; 28, identifier:modules; 29, block; 29, 30; 29, 38; 30, expression_statement; 30, 31; 31, assignment; 31, 32; 31, 33; 32, identifier:md; 33, subscript; 33, 34; 33, 37; 34, attribute; 34, 35; 34, 36; 35, identifier:sys; 36, identifier:modules; 37, identifier:md; 38, if_statement; 38, 39; 38, 42; 39, comparison_operator:is; 39, 40; 39, 41; 40, identifier:md; 41, None; 42, block; 42, 43; 43, return_statement; 43, 44; 44, identifier:md; 45, elif_clause; 45, 46; 45, 53; 45, 54; 46, comparison_operator:in; 46, 47; 46, 48; 47, identifier:md; 48, attribute; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:pytypes; 51, identifier:typechecker; 52, identifier:_pending_modules; 53, comment; 54, block; 54, 55; 54, 68; 55, expression_statement; 55, 56; 56, call; 56, 57; 56, 66; 57, attribute; 57, 58; 57, 65; 58, subscript; 58, 59; 58, 64; 59, attribute; 59, 60; 59, 63; 60, attribute; 60, 61; 60, 62; 61, identifier:pytypes; 62, identifier:typechecker; 63, identifier:_pending_modules; 64, identifier:md; 65, identifier:append; 66, argument_list; 66, 67; 67, identifier:typelogged_module; 68, return_statement; 68, 69; 69, identifier:md; 70, assert_statement; 70, 71; 71, parenthesized_expression; 71, 72; 72, call; 72, 73; 72, 74; 73, identifier:ismodule; 74, argument_list; 74, 75; 75, identifier:md; 76, if_statement; 76, 77; 76, 86; 76, 87; 77, comparison_operator:in; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:md; 80, identifier:__name__; 81, attribute; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:pytypes; 84, identifier:typechecker; 85, identifier:_pending_modules; 86, comment; 87, block; 87, 88; 87, 103; 87, 104; 88, expression_statement; 88, 89; 89, call; 89, 90; 89, 101; 90, attribute; 90, 91; 90, 100; 91, subscript; 91, 92; 91, 97; 92, attribute; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:pytypes; 95, identifier:typechecker; 96, identifier:_pending_modules; 97, attribute; 97, 98; 97, 99; 98, identifier:md; 99, identifier:__name__; 100, identifier:append; 101, argument_list; 101, 102; 102, identifier:typelogged_module; 103, comment; 104, comment; 105, assert_statement; 105, 106; 106, parenthesized_expression; 106, 107; 107, call; 107, 108; 107, 109; 108, identifier:ismodule; 109, argument_list; 109, 110; 110, identifier:md; 111, if_statement; 111, 112; 111, 131; 112, boolean_operator:and; 112, 113; 112, 118; 112, 119; 113, comparison_operator:in; 113, 114; 113, 117; 114, attribute; 114, 115; 114, 116; 115, identifier:md; 116, identifier:__name__; 117, identifier:_fully_typelogged_modules; 118, line_continuation:\; 119, comparison_operator:==; 119, 120; 119, 125; 120, subscript; 120, 121; 120, 122; 121, identifier:_fully_typelogged_modules; 122, attribute; 122, 123; 122, 124; 123, identifier:md; 124, identifier:__name__; 125, call; 125, 126; 125, 127; 126, identifier:len; 127, argument_list; 127, 128; 128, attribute; 128, 129; 128, 130; 129, identifier:md; 130, identifier:__dict__; 131, block; 131, 132; 132, return_statement; 132, 133; 133, identifier:md; 134, comment; 135, comment; 136, comment; 137, comment; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:keys; 141, list_comprehension; 141, 142; 141, 143; 142, identifier:key; 143, for_in_clause; 143, 144; 143, 145; 144, identifier:key; 145, attribute; 145, 146; 145, 147; 146, identifier:md; 147, identifier:__dict__; 148, for_statement; 148, 149; 148, 150; 148, 151; 149, identifier:key; 150, identifier:keys; 151, block; 151, 152; 151, 160; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:memb; 155, subscript; 155, 156; 155, 159; 156, attribute; 156, 157; 156, 158; 157, identifier:md; 158, identifier:__dict__; 159, identifier:key; 160, if_statement; 160, 161; 160, 173; 160, 184; 161, boolean_operator:and; 161, 162; 161, 166; 162, call; 162, 163; 162, 164; 163, identifier:_check_as_func; 164, argument_list; 164, 165; 165, identifier:memb; 166, comparison_operator:==; 166, 167; 166, 170; 167, attribute; 167, 168; 167, 169; 168, identifier:memb; 169, identifier:__module__; 170, attribute; 170, 171; 170, 172; 171, identifier:md; 172, identifier:__name__; 173, block; 173, 174; 174, expression_statement; 174, 175; 175, call; 175, 176; 175, 177; 176, identifier:setattr; 177, argument_list; 177, 178; 177, 179; 177, 180; 178, identifier:md; 179, identifier:key; 180, call; 180, 181; 180, 182; 181, identifier:typelogged_func; 182, argument_list; 182, 183; 183, identifier:memb; 184, elif_clause; 184, 185; 184, 197; 185, boolean_operator:and; 185, 186; 185, 190; 186, call; 186, 187; 186, 188; 187, identifier:isclass; 188, argument_list; 188, 189; 189, identifier:memb; 190, comparison_operator:==; 190, 191; 190, 194; 191, attribute; 191, 192; 191, 193; 192, identifier:memb; 193, identifier:__module__; 194, attribute; 194, 195; 194, 196; 195, identifier:md; 196, identifier:__name__; 197, block; 197, 198; 198, expression_statement; 198, 199; 199, call; 199, 200; 199, 201; 200, identifier:typelogged_class; 201, argument_list; 201, 202; 202, identifier:memb; 203, if_statement; 203, 204; 203, 214; 204, not_operator; 204, 205; 205, comparison_operator:in; 205, 206; 205, 209; 206, attribute; 206, 207; 206, 208; 207, identifier:md; 208, identifier:__name__; 209, attribute; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:pytypes; 212, identifier:typechecker; 213, identifier:_pending_modules; 214, block; 214, 215; 215, expression_statement; 215, 216; 216, assignment; 216, 217; 216, 222; 217, subscript; 217, 218; 217, 219; 218, identifier:_fully_typelogged_modules; 219, attribute; 219, 220; 219, 221; 220, identifier:md; 221, identifier:__name__; 222, call; 222, 223; 222, 224; 223, identifier:len; 224, argument_list; 224, 225; 225, attribute; 225, 226; 225, 227; 226, identifier:md; 227, identifier:__dict__; 228, return_statement; 228, 229; 229, identifier:md
def typelogged_module(md): """Works like typelogged, but is only applicable to modules by explicit call). md must be a module or a module name contained in sys.modules. """ if not pytypes.typelogging_enabled: return md if isinstance(md, str): if md in sys.modules: md = sys.modules[md] if md is None: return md elif md in pytypes.typechecker._pending_modules: # if import is pending, we just store this call for later pytypes.typechecker._pending_modules[md].append(typelogged_module) return md assert(ismodule(md)) if md.__name__ in pytypes.typechecker._pending_modules: # if import is pending, we just store this call for later pytypes.typechecker._pending_modules[md.__name__].append(typelogged_module) # we already process the module now as far as possible for its internal use # todo: Issue warning here that not the whole module might be covered yet assert(ismodule(md)) if md.__name__ in _fully_typelogged_modules and \ _fully_typelogged_modules[md.__name__] == len(md.__dict__): return md # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here keys = [key for key in md.__dict__] for key in keys: memb = md.__dict__[key] if _check_as_func(memb) and memb.__module__ == md.__name__: setattr(md, key, typelogged_func(memb)) elif isclass(memb) and memb.__module__ == md.__name__: typelogged_class(memb) if not md.__name__ in pytypes.typechecker._pending_modules: _fully_typelogged_modules[md.__name__] = len(md.__dict__) return md
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:import_process_elements; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 8; 4, identifier:document; 5, identifier:diagram_graph; 6, identifier:sequence_flows; 7, identifier:process_elements_dict; 8, identifier:plane_element; 9, block; 9, 10; 9, 12; 10, expression_statement; 10, 11; 11, comment; 12, for_statement; 12, 13; 12, 14; 12, 25; 13, identifier:process_element; 14, call; 14, 15; 14, 18; 15, attribute; 15, 16; 15, 17; 16, identifier:document; 17, identifier:getElementsByTagNameNS; 18, argument_list; 18, 19; 18, 20; 19, string:"*"; 20, attribute; 20, 21; 20, 24; 21, attribute; 21, 22; 21, 23; 22, identifier:consts; 23, identifier:Consts; 24, identifier:process; 25, block; 25, 26; 25, 34; 25, 47; 25, 53; 25, 67; 25, 95; 25, 140; 26, expression_statement; 26, 27; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:BpmnDiagramGraphImport; 30, identifier:import_process_element; 31, argument_list; 31, 32; 31, 33; 32, identifier:process_elements_dict; 33, identifier:process_element; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:process_id; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:process_element; 40, identifier:getAttribute; 41, argument_list; 41, 42; 42, attribute; 42, 43; 42, 46; 43, attribute; 43, 44; 43, 45; 44, identifier:consts; 45, identifier:Consts; 46, identifier:id; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:process_attributes; 50, subscript; 50, 51; 50, 52; 51, identifier:process_elements_dict; 52, identifier:process_id; 53, expression_statement; 53, 54; 54, assignment; 54, 55; 54, 56; 55, identifier:lane_set_list; 56, call; 56, 57; 56, 60; 57, attribute; 57, 58; 57, 59; 58, identifier:process_element; 59, identifier:getElementsByTagNameNS; 60, argument_list; 60, 61; 60, 62; 61, string:"*"; 62, attribute; 62, 63; 62, 66; 63, attribute; 63, 64; 63, 65; 64, identifier:consts; 65, identifier:Consts; 66, identifier:lane_set; 67, if_statement; 67, 68; 67, 78; 67, 79; 68, boolean_operator:and; 68, 69; 68, 72; 69, comparison_operator:is; 69, 70; 69, 71; 70, identifier:lane_set_list; 71, None; 72, comparison_operator:>; 72, 73; 72, 77; 73, call; 73, 74; 73, 75; 74, identifier:len; 75, argument_list; 75, 76; 76, identifier:lane_set_list; 77, integer:0; 78, comment; 79, block; 79, 80; 79, 86; 80, expression_statement; 80, 81; 81, assignment; 81, 82; 81, 83; 82, identifier:lane_set; 83, subscript; 83, 84; 83, 85; 84, identifier:lane_set_list; 85, integer:0; 86, expression_statement; 86, 87; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:BpmnDiagramGraphImport; 90, identifier:import_lane_set_element; 91, argument_list; 91, 92; 91, 93; 91, 94; 92, identifier:process_attributes; 93, identifier:lane_set; 94, identifier:plane_element; 95, for_statement; 95, 96; 95, 97; 95, 105; 96, identifier:element; 97, call; 97, 98; 97, 103; 98, attribute; 98, 99; 98, 102; 99, attribute; 99, 100; 99, 101; 100, identifier:utils; 101, identifier:BpmnImportUtils; 102, identifier:iterate_elements; 103, argument_list; 103, 104; 104, identifier:process_element; 105, block; 105, 106; 106, if_statement; 106, 107; 106, 114; 107, comparison_operator:!=; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:element; 110, identifier:nodeType; 111, attribute; 111, 112; 111, 113; 112, identifier:element; 113, identifier:TEXT_NODE; 114, block; 114, 115; 114, 128; 115, expression_statement; 115, 116; 116, assignment; 116, 117; 116, 118; 117, identifier:tag_name; 118, call; 118, 119; 118, 124; 119, attribute; 119, 120; 119, 123; 120, attribute; 120, 121; 120, 122; 121, identifier:utils; 122, identifier:BpmnImportUtils; 123, identifier:remove_namespace_from_tag_name; 124, argument_list; 124, 125; 125, attribute; 125, 126; 125, 127; 126, identifier:element; 127, identifier:tagName; 128, expression_statement; 128, 129; 129, call; 129, 130; 129, 133; 130, attribute; 130, 131; 130, 132; 131, identifier:BpmnDiagramGraphImport; 132, identifier:__import_element_by_tag_name; 133, argument_list; 133, 134; 133, 135; 133, 136; 133, 137; 133, 138; 133, 139; 134, identifier:diagram_graph; 135, identifier:sequence_flows; 136, identifier:process_id; 137, identifier:process_attributes; 138, identifier:element; 139, identifier:tag_name; 140, for_statement; 140, 141; 140, 142; 140, 150; 141, identifier:flow; 142, call; 142, 143; 142, 148; 143, attribute; 143, 144; 143, 147; 144, attribute; 144, 145; 144, 146; 145, identifier:utils; 146, identifier:BpmnImportUtils; 147, identifier:iterate_elements; 148, argument_list; 148, 149; 149, identifier:process_element; 150, block; 150, 151; 151, if_statement; 151, 152; 151, 159; 152, comparison_operator:!=; 152, 153; 152, 156; 153, attribute; 153, 154; 153, 155; 154, identifier:flow; 155, identifier:nodeType; 156, attribute; 156, 157; 156, 158; 157, identifier:flow; 158, identifier:TEXT_NODE; 159, block; 159, 160; 159, 173; 160, expression_statement; 160, 161; 161, assignment; 161, 162; 161, 163; 162, identifier:tag_name; 163, call; 163, 164; 163, 169; 164, attribute; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:utils; 167, identifier:BpmnImportUtils; 168, identifier:remove_namespace_from_tag_name; 169, argument_list; 169, 170; 170, attribute; 170, 171; 170, 172; 171, identifier:flow; 172, identifier:tagName; 173, if_statement; 173, 174; 173, 181; 174, comparison_operator:==; 174, 175; 174, 176; 175, identifier:tag_name; 176, attribute; 176, 177; 176, 180; 177, attribute; 177, 178; 177, 179; 178, identifier:consts; 179, identifier:Consts; 180, identifier:sequence_flow; 181, block; 181, 182; 182, expression_statement; 182, 183; 183, call; 183, 184; 183, 187; 184, attribute; 184, 185; 184, 186; 185, identifier:BpmnDiagramGraphImport; 186, identifier:import_sequence_flow_to_graph; 187, argument_list; 187, 188; 187, 189; 187, 190; 187, 191; 188, identifier:diagram_graph; 189, identifier:sequence_flows; 190, identifier:process_id; 191, identifier:flow
def import_process_elements(document, diagram_graph, sequence_flows, process_elements_dict, plane_element): """ Method for importing all 'process' elements in diagram. :param document: XML document, :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param sequence_flows: a list of sequence flows existing in diagram, :param process_elements_dict: dictionary that holds attribute values for imported 'process' elements. Key is an ID of process, value - a dictionary of process attributes, :param plane_element: object representing a BPMN XML 'plane' element. """ for process_element in document.getElementsByTagNameNS("*", consts.Consts.process): BpmnDiagramGraphImport.import_process_element(process_elements_dict, process_element) process_id = process_element.getAttribute(consts.Consts.id) process_attributes = process_elements_dict[process_id] lane_set_list = process_element.getElementsByTagNameNS("*", consts.Consts.lane_set) if lane_set_list is not None and len(lane_set_list) > 0: # according to BPMN 2.0 XML Schema, there's at most one 'laneSet' element inside 'process' lane_set = lane_set_list[0] BpmnDiagramGraphImport.import_lane_set_element(process_attributes, lane_set, plane_element) for element in utils.BpmnImportUtils.iterate_elements(process_element): if element.nodeType != element.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(element.tagName) BpmnDiagramGraphImport.__import_element_by_tag_name(diagram_graph, sequence_flows, process_id, process_attributes, element, tag_name) for flow in utils.BpmnImportUtils.iterate_elements(process_element): if flow.nodeType != flow.TEXT_NODE: tag_name = utils.BpmnImportUtils.remove_namespace_from_tag_name(flow.tagName) if tag_name == consts.Consts.sequence_flow: BpmnDiagramGraphImport.import_sequence_flow_to_graph(diagram_graph, sequence_flows, process_id, flow)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:generate_nodes_clasification; 3, parameters; 3, 4; 4, identifier:bpmn_diagram; 5, block; 5, 6; 5, 8; 5, 12; 5, 16; 5, 20; 5, 24; 5, 37; 5, 55; 5, 68; 5, 86; 5, 99; 5, 117; 5, 130; 5, 148; 5, 161; 5, 179; 5, 192; 5, 210; 5, 223; 5, 241; 5, 254; 5, 273; 5, 286; 5, 304; 5, 317; 5, 336; 5, 349; 5, 367; 6, expression_statement; 6, 7; 7, comment; 8, expression_statement; 8, 9; 9, assignment; 9, 10; 9, 11; 10, identifier:nodes_classification; 11, dictionary; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:classification_element; 15, string:"Element"; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:classification_start_event; 19, string:"Start Event"; 20, expression_statement; 20, 21; 21, assignment; 21, 22; 21, 23; 22, identifier:classification_end_event; 23, string:"End Event"; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:task_list; 27, call; 27, 28; 27, 31; 28, attribute; 28, 29; 28, 30; 29, identifier:bpmn_diagram; 30, identifier:get_nodes; 31, argument_list; 31, 32; 32, attribute; 32, 33; 32, 36; 33, attribute; 33, 34; 33, 35; 34, identifier:consts; 35, identifier:Consts; 36, identifier:task; 37, for_statement; 37, 38; 37, 39; 37, 40; 38, identifier:element; 39, identifier:task_list; 40, block; 40, 41; 40, 46; 41, expression_statement; 41, 42; 42, assignment; 42, 43; 42, 44; 43, identifier:classification_labels; 44, list:[classification_element]; 44, 45; 45, identifier:classification_element; 46, expression_statement; 46, 47; 47, call; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:BpmnImportUtils; 50, identifier:split_join_classification; 51, argument_list; 51, 52; 51, 53; 51, 54; 52, identifier:element; 53, identifier:classification_labels; 54, identifier:nodes_classification; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:subprocess_list; 58, call; 58, 59; 58, 62; 59, attribute; 59, 60; 59, 61; 60, identifier:bpmn_diagram; 61, identifier:get_nodes; 62, argument_list; 62, 63; 63, attribute; 63, 64; 63, 67; 64, attribute; 64, 65; 64, 66; 65, identifier:consts; 66, identifier:Consts; 67, identifier:subprocess; 68, for_statement; 68, 69; 68, 70; 68, 71; 69, identifier:element; 70, identifier:subprocess_list; 71, block; 71, 72; 71, 77; 72, expression_statement; 72, 73; 73, assignment; 73, 74; 73, 75; 74, identifier:classification_labels; 75, list:[classification_element]; 75, 76; 76, identifier:classification_element; 77, expression_statement; 77, 78; 78, call; 78, 79; 78, 82; 79, attribute; 79, 80; 79, 81; 80, identifier:BpmnImportUtils; 81, identifier:split_join_classification; 82, argument_list; 82, 83; 82, 84; 82, 85; 83, identifier:element; 84, identifier:classification_labels; 85, identifier:nodes_classification; 86, expression_statement; 86, 87; 87, assignment; 87, 88; 87, 89; 88, identifier:complex_gateway_list; 89, call; 89, 90; 89, 93; 90, attribute; 90, 91; 90, 92; 91, identifier:bpmn_diagram; 92, identifier:get_nodes; 93, argument_list; 93, 94; 94, attribute; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:consts; 97, identifier:Consts; 98, identifier:complex_gateway; 99, for_statement; 99, 100; 99, 101; 99, 102; 100, identifier:element; 101, identifier:complex_gateway_list; 102, block; 102, 103; 102, 108; 103, expression_statement; 103, 104; 104, assignment; 104, 105; 104, 106; 105, identifier:classification_labels; 106, list:[classification_element]; 106, 107; 107, identifier:classification_element; 108, expression_statement; 108, 109; 109, call; 109, 110; 109, 113; 110, attribute; 110, 111; 110, 112; 111, identifier:BpmnImportUtils; 112, identifier:split_join_classification; 113, argument_list; 113, 114; 113, 115; 113, 116; 114, identifier:element; 115, identifier:classification_labels; 116, identifier:nodes_classification; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 120; 119, identifier:event_based_gateway_list; 120, call; 120, 121; 120, 124; 121, attribute; 121, 122; 121, 123; 122, identifier:bpmn_diagram; 123, identifier:get_nodes; 124, argument_list; 124, 125; 125, attribute; 125, 126; 125, 129; 126, attribute; 126, 127; 126, 128; 127, identifier:consts; 128, identifier:Consts; 129, identifier:event_based_gateway; 130, for_statement; 130, 131; 130, 132; 130, 133; 131, identifier:element; 132, identifier:event_based_gateway_list; 133, block; 133, 134; 133, 139; 134, expression_statement; 134, 135; 135, assignment; 135, 136; 135, 137; 136, identifier:classification_labels; 137, list:[classification_element]; 137, 138; 138, identifier:classification_element; 139, expression_statement; 139, 140; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:BpmnImportUtils; 143, identifier:split_join_classification; 144, argument_list; 144, 145; 144, 146; 144, 147; 145, identifier:element; 146, identifier:classification_labels; 147, identifier:nodes_classification; 148, expression_statement; 148, 149; 149, assignment; 149, 150; 149, 151; 150, identifier:inclusive_gateway_list; 151, call; 151, 152; 151, 155; 152, attribute; 152, 153; 152, 154; 153, identifier:bpmn_diagram; 154, identifier:get_nodes; 155, argument_list; 155, 156; 156, attribute; 156, 157; 156, 160; 157, attribute; 157, 158; 157, 159; 158, identifier:consts; 159, identifier:Consts; 160, identifier:inclusive_gateway; 161, for_statement; 161, 162; 161, 163; 161, 164; 162, identifier:element; 163, identifier:inclusive_gateway_list; 164, block; 164, 165; 164, 170; 165, expression_statement; 165, 166; 166, assignment; 166, 167; 166, 168; 167, identifier:classification_labels; 168, list:[classification_element]; 168, 169; 169, identifier:classification_element; 170, expression_statement; 170, 171; 171, call; 171, 172; 171, 175; 172, attribute; 172, 173; 172, 174; 173, identifier:BpmnImportUtils; 174, identifier:split_join_classification; 175, argument_list; 175, 176; 175, 177; 175, 178; 176, identifier:element; 177, identifier:classification_labels; 178, identifier:nodes_classification; 179, expression_statement; 179, 180; 180, assignment; 180, 181; 180, 182; 181, identifier:exclusive_gateway_list; 182, call; 182, 183; 182, 186; 183, attribute; 183, 184; 183, 185; 184, identifier:bpmn_diagram; 185, identifier:get_nodes; 186, argument_list; 186, 187; 187, attribute; 187, 188; 187, 191; 188, attribute; 188, 189; 188, 190; 189, identifier:consts; 190, identifier:Consts; 191, identifier:exclusive_gateway; 192, for_statement; 192, 193; 192, 194; 192, 195; 193, identifier:element; 194, identifier:exclusive_gateway_list; 195, block; 195, 196; 195, 201; 196, expression_statement; 196, 197; 197, assignment; 197, 198; 197, 199; 198, identifier:classification_labels; 199, list:[classification_element]; 199, 200; 200, identifier:classification_element; 201, expression_statement; 201, 202; 202, call; 202, 203; 202, 206; 203, attribute; 203, 204; 203, 205; 204, identifier:BpmnImportUtils; 205, identifier:split_join_classification; 206, argument_list; 206, 207; 206, 208; 206, 209; 207, identifier:element; 208, identifier:classification_labels; 209, identifier:nodes_classification; 210, expression_statement; 210, 211; 211, assignment; 211, 212; 211, 213; 212, identifier:parallel_gateway_list; 213, call; 213, 214; 213, 217; 214, attribute; 214, 215; 214, 216; 215, identifier:bpmn_diagram; 216, identifier:get_nodes; 217, argument_list; 217, 218; 218, attribute; 218, 219; 218, 222; 219, attribute; 219, 220; 219, 221; 220, identifier:consts; 221, identifier:Consts; 222, identifier:parallel_gateway; 223, for_statement; 223, 224; 223, 225; 223, 226; 224, identifier:element; 225, identifier:parallel_gateway_list; 226, block; 226, 227; 226, 232; 227, expression_statement; 227, 228; 228, assignment; 228, 229; 228, 230; 229, identifier:classification_labels; 230, list:[classification_element]; 230, 231; 231, identifier:classification_element; 232, expression_statement; 232, 233; 233, call; 233, 234; 233, 237; 234, attribute; 234, 235; 234, 236; 235, identifier:BpmnImportUtils; 236, identifier:split_join_classification; 237, argument_list; 237, 238; 237, 239; 237, 240; 238, identifier:element; 239, identifier:classification_labels; 240, identifier:nodes_classification; 241, expression_statement; 241, 242; 242, assignment; 242, 243; 242, 244; 243, identifier:start_event_list; 244, call; 244, 245; 244, 248; 245, attribute; 245, 246; 245, 247; 246, identifier:bpmn_diagram; 247, identifier:get_nodes; 248, argument_list; 248, 249; 249, attribute; 249, 250; 249, 253; 250, attribute; 250, 251; 250, 252; 251, identifier:consts; 252, identifier:Consts; 253, identifier:start_event; 254, for_statement; 254, 255; 254, 256; 254, 257; 255, identifier:element; 256, identifier:start_event_list; 257, block; 257, 258; 257, 264; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:classification_labels; 261, list:[classification_element, classification_start_event]; 261, 262; 261, 263; 262, identifier:classification_element; 263, identifier:classification_start_event; 264, expression_statement; 264, 265; 265, call; 265, 266; 265, 269; 266, attribute; 266, 267; 266, 268; 267, identifier:BpmnImportUtils; 268, identifier:split_join_classification; 269, argument_list; 269, 270; 269, 271; 269, 272; 270, identifier:element; 271, identifier:classification_labels; 272, identifier:nodes_classification; 273, expression_statement; 273, 274; 274, assignment; 274, 275; 274, 276; 275, identifier:intermediate_catch_event_list; 276, call; 276, 277; 276, 280; 277, attribute; 277, 278; 277, 279; 278, identifier:bpmn_diagram; 279, identifier:get_nodes; 280, argument_list; 280, 281; 281, attribute; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:consts; 284, identifier:Consts; 285, identifier:intermediate_catch_event; 286, for_statement; 286, 287; 286, 288; 286, 289; 287, identifier:element; 288, identifier:intermediate_catch_event_list; 289, block; 289, 290; 289, 295; 290, expression_statement; 290, 291; 291, assignment; 291, 292; 291, 293; 292, identifier:classification_labels; 293, list:[classification_element]; 293, 294; 294, identifier:classification_element; 295, expression_statement; 295, 296; 296, call; 296, 297; 296, 300; 297, attribute; 297, 298; 297, 299; 298, identifier:BpmnImportUtils; 299, identifier:split_join_classification; 300, argument_list; 300, 301; 300, 302; 300, 303; 301, identifier:element; 302, identifier:classification_labels; 303, identifier:nodes_classification; 304, expression_statement; 304, 305; 305, assignment; 305, 306; 305, 307; 306, identifier:end_event_list; 307, call; 307, 308; 307, 311; 308, attribute; 308, 309; 308, 310; 309, identifier:bpmn_diagram; 310, identifier:get_nodes; 311, argument_list; 311, 312; 312, attribute; 312, 313; 312, 316; 313, attribute; 313, 314; 313, 315; 314, identifier:consts; 315, identifier:Consts; 316, identifier:end_event; 317, for_statement; 317, 318; 317, 319; 317, 320; 318, identifier:element; 319, identifier:end_event_list; 320, block; 320, 321; 320, 327; 321, expression_statement; 321, 322; 322, assignment; 322, 323; 322, 324; 323, identifier:classification_labels; 324, list:[classification_element, classification_end_event]; 324, 325; 324, 326; 325, identifier:classification_element; 326, identifier:classification_end_event; 327, expression_statement; 327, 328; 328, call; 328, 329; 328, 332; 329, attribute; 329, 330; 329, 331; 330, identifier:BpmnImportUtils; 331, identifier:split_join_classification; 332, argument_list; 332, 333; 332, 334; 332, 335; 333, identifier:element; 334, identifier:classification_labels; 335, identifier:nodes_classification; 336, expression_statement; 336, 337; 337, assignment; 337, 338; 337, 339; 338, identifier:intermediate_throw_event_list; 339, call; 339, 340; 339, 343; 340, attribute; 340, 341; 340, 342; 341, identifier:bpmn_diagram; 342, identifier:get_nodes; 343, argument_list; 343, 344; 344, attribute; 344, 345; 344, 348; 345, attribute; 345, 346; 345, 347; 346, identifier:consts; 347, identifier:Consts; 348, identifier:intermediate_throw_event; 349, for_statement; 349, 350; 349, 351; 349, 352; 350, identifier:element; 351, identifier:intermediate_throw_event_list; 352, block; 352, 353; 352, 358; 353, expression_statement; 353, 354; 354, assignment; 354, 355; 354, 356; 355, identifier:classification_labels; 356, list:[classification_element]; 356, 357; 357, identifier:classification_element; 358, expression_statement; 358, 359; 359, call; 359, 360; 359, 363; 360, attribute; 360, 361; 360, 362; 361, identifier:BpmnImportUtils; 362, identifier:split_join_classification; 363, argument_list; 363, 364; 363, 365; 363, 366; 364, identifier:element; 365, identifier:classification_labels; 366, identifier:nodes_classification; 367, return_statement; 367, 368; 368, identifier:nodes_classification
def generate_nodes_clasification(bpmn_diagram): """ Diagram elements classification. Implementation based on article "A Simple Algorithm for Automatic Layout of BPMN Processes". Assigns a classification to the diagram element according to specific element parameters. - Element - every element of the process which is not an edge, - Start Event - all types of start events, - End Event - all types of end events, - Join - an element with more than one incoming edge, - Split - an element with more than one outgoing edge. :param bpmn_diagram: BPMNDiagramGraph class instance representing a BPMN process diagram. :return: a dictionary of classification labels. Key - node id. Values - a list of labels. """ nodes_classification = {} classification_element = "Element" classification_start_event = "Start Event" classification_end_event = "End Event" task_list = bpmn_diagram.get_nodes(consts.Consts.task) for element in task_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) subprocess_list = bpmn_diagram.get_nodes(consts.Consts.subprocess) for element in subprocess_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) complex_gateway_list = bpmn_diagram.get_nodes(consts.Consts.complex_gateway) for element in complex_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) event_based_gateway_list = bpmn_diagram.get_nodes(consts.Consts.event_based_gateway) for element in event_based_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) inclusive_gateway_list = bpmn_diagram.get_nodes(consts.Consts.inclusive_gateway) for element in inclusive_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) exclusive_gateway_list = bpmn_diagram.get_nodes(consts.Consts.exclusive_gateway) for element in exclusive_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) parallel_gateway_list = bpmn_diagram.get_nodes(consts.Consts.parallel_gateway) for element in parallel_gateway_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) start_event_list = bpmn_diagram.get_nodes(consts.Consts.start_event) for element in start_event_list: classification_labels = [classification_element, classification_start_event] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) intermediate_catch_event_list = bpmn_diagram.get_nodes(consts.Consts.intermediate_catch_event) for element in intermediate_catch_event_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) end_event_list = bpmn_diagram.get_nodes(consts.Consts.end_event) for element in end_event_list: classification_labels = [classification_element, classification_end_event] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) intermediate_throw_event_list = bpmn_diagram.get_nodes(consts.Consts.intermediate_throw_event) for element in intermediate_throw_event_list: classification_labels = [classification_element] BpmnImportUtils.split_join_classification(element, classification_labels, nodes_classification) return nodes_classification
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:hclust_linearize; 3, parameters; 3, 4; 4, identifier:U; 5, block; 5, 6; 5, 8; 5, 14; 5, 23; 6, expression_statement; 6, 7; 7, comment; 8, import_from_statement; 8, 9; 8, 12; 9, dotted_name; 9, 10; 9, 11; 10, identifier:scipy; 11, identifier:cluster; 12, dotted_name; 12, 13; 13, identifier:hierarchy; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:Z; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:hierarchy; 20, identifier:ward; 21, argument_list; 21, 22; 22, identifier:U; 23, return_statement; 23, 24; 24, call; 24, 25; 24, 28; 25, attribute; 25, 26; 25, 27; 26, identifier:hierarchy; 27, identifier:leaves_list; 28, argument_list; 28, 29; 29, call; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:hierarchy; 32, identifier:optimal_leaf_ordering; 33, argument_list; 33, 34; 33, 35; 34, identifier:Z; 35, identifier:U
def hclust_linearize(U): """Sorts the rows of a matrix by hierarchical clustering. Parameters: U (ndarray) : matrix of data Returns: prm (ndarray) : permutation of the rows """ from scipy.cluster import hierarchy Z = hierarchy.ward(U) return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:kruskal_align; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:U; 5, identifier:V; 6, default_parameter; 6, 7; 6, 8; 7, identifier:permute_U; 8, False; 9, default_parameter; 9, 10; 9, 11; 10, identifier:permute_V; 11, False; 12, block; 12, 13; 12, 15; 12, 16; 12, 38; 12, 60; 12, 82; 12, 101; 12, 102; 12, 117; 12, 127; 12, 128; 12, 142; 12, 143; 12, 163; 12, 183; 12, 184; 12, 235; 12, 236; 12, 246; 12, 256; 12, 257; 12, 267; 12, 277; 12, 278; 12, 294; 12, 308; 12, 309; 12, 349; 12, 350; 13, expression_statement; 13, 14; 14, comment; 15, comment; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:unrm; 19, list_comprehension; 19, 20; 19, 33; 20, binary_operator:/; 20, 21; 20, 22; 21, identifier:f; 22, call; 22, 23; 22, 28; 23, attribute; 23, 24; 23, 27; 24, attribute; 24, 25; 24, 26; 25, identifier:np; 26, identifier:linalg; 27, identifier:norm; 28, argument_list; 28, 29; 28, 30; 29, identifier:f; 30, keyword_argument; 30, 31; 30, 32; 31, identifier:axis; 32, integer:0; 33, for_in_clause; 33, 34; 33, 35; 34, identifier:f; 35, attribute; 35, 36; 35, 37; 36, identifier:U; 37, identifier:factors; 38, expression_statement; 38, 39; 39, assignment; 39, 40; 39, 41; 40, identifier:vnrm; 41, list_comprehension; 41, 42; 41, 55; 42, binary_operator:/; 42, 43; 42, 44; 43, identifier:f; 44, call; 44, 45; 44, 50; 45, attribute; 45, 46; 45, 49; 46, attribute; 46, 47; 46, 48; 47, identifier:np; 48, identifier:linalg; 49, identifier:norm; 50, argument_list; 50, 51; 50, 52; 51, identifier:f; 52, keyword_argument; 52, 53; 52, 54; 53, identifier:axis; 54, integer:0; 55, for_in_clause; 55, 56; 55, 57; 56, identifier:f; 57, attribute; 57, 58; 57, 59; 58, identifier:V; 59, identifier:factors; 60, expression_statement; 60, 61; 61, assignment; 61, 62; 61, 63; 62, identifier:sim_matrices; 63, list_comprehension; 63, 64; 63, 73; 64, call; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:np; 67, identifier:dot; 68, argument_list; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:u; 71, identifier:T; 72, identifier:v; 73, for_in_clause; 73, 74; 73, 77; 74, pattern_list; 74, 75; 74, 76; 75, identifier:u; 76, identifier:v; 77, call; 77, 78; 77, 79; 78, identifier:zip; 79, argument_list; 79, 80; 79, 81; 80, identifier:unrm; 81, identifier:vnrm; 82, expression_statement; 82, 83; 83, assignment; 83, 84; 83, 85; 84, identifier:cost; 85, binary_operator:-; 85, 86; 85, 87; 86, integer:1; 87, call; 87, 88; 87, 91; 88, attribute; 88, 89; 88, 90; 89, identifier:np; 90, identifier:mean; 91, argument_list; 91, 92; 91, 98; 92, call; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:np; 95, identifier:abs; 96, argument_list; 96, 97; 97, identifier:sim_matrices; 98, keyword_argument; 98, 99; 98, 100; 99, identifier:axis; 100, integer:0; 101, comment; 102, expression_statement; 102, 103; 103, assignment; 103, 104; 103, 105; 104, identifier:indices; 105, call; 105, 106; 105, 111; 106, attribute; 106, 107; 106, 110; 107, call; 107, 108; 107, 109; 108, identifier:Munkres; 109, argument_list; 110, identifier:compute; 111, argument_list; 111, 112; 112, call; 112, 113; 112, 116; 113, attribute; 113, 114; 113, 115; 114, identifier:cost; 115, identifier:copy; 116, argument_list; 117, expression_statement; 117, 118; 118, assignment; 118, 119; 118, 122; 119, pattern_list; 119, 120; 119, 121; 120, identifier:prmU; 121, identifier:prmV; 122, call; 122, 123; 122, 124; 123, identifier:zip; 124, argument_list; 124, 125; 125, list_splat; 125, 126; 126, identifier:indices; 127, comment; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 131; 130, identifier:similarity; 131, call; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:np; 134, identifier:mean; 135, argument_list; 135, 136; 136, binary_operator:-; 136, 137; 136, 138; 137, integer:1; 138, subscript; 138, 139; 138, 140; 138, 141; 139, identifier:cost; 140, identifier:prmU; 141, identifier:prmV; 142, comment; 143, expression_statement; 143, 144; 144, assignment; 144, 145; 144, 146; 145, identifier:unmatched_U; 146, call; 146, 147; 146, 148; 147, identifier:list; 148, argument_list; 148, 149; 149, binary_operator:-; 149, 150; 149, 159; 150, call; 150, 151; 150, 152; 151, identifier:set; 152, argument_list; 152, 153; 153, call; 153, 154; 153, 155; 154, identifier:range; 155, argument_list; 155, 156; 156, attribute; 156, 157; 156, 158; 157, identifier:U; 158, identifier:rank; 159, call; 159, 160; 159, 161; 160, identifier:set; 161, argument_list; 161, 162; 162, identifier:prmU; 163, expression_statement; 163, 164; 164, assignment; 164, 165; 164, 166; 165, identifier:unmatched_V; 166, call; 166, 167; 166, 168; 167, identifier:list; 168, argument_list; 168, 169; 169, binary_operator:-; 169, 170; 169, 179; 170, call; 170, 171; 170, 172; 171, identifier:set; 172, argument_list; 172, 173; 173, call; 173, 174; 173, 175; 174, identifier:range; 175, argument_list; 175, 176; 176, attribute; 176, 177; 176, 178; 177, identifier:V; 178, identifier:rank; 179, call; 179, 180; 179, 181; 180, identifier:set; 181, argument_list; 181, 182; 182, identifier:prmV; 183, comment; 184, if_statement; 184, 185; 184, 188; 184, 201; 184, 202; 184, 203; 184, 215; 184, 216; 184, 217; 184, 229; 184, 230; 184, 231; 185, boolean_operator:and; 185, 186; 185, 187; 186, identifier:permute_U; 187, identifier:permute_V; 188, block; 188, 189; 189, expression_statement; 189, 190; 190, assignment; 190, 191; 190, 192; 191, identifier:idx; 192, call; 192, 193; 192, 196; 193, attribute; 193, 194; 193, 195; 194, identifier:np; 195, identifier:argsort; 196, argument_list; 196, 197; 197, subscript; 197, 198; 197, 199; 197, 200; 198, identifier:cost; 199, identifier:prmU; 200, identifier:prmV; 201, comment; 202, comment; 203, elif_clause; 203, 204; 203, 205; 204, identifier:permute_V; 205, block; 205, 206; 206, expression_statement; 206, 207; 207, assignment; 207, 208; 207, 209; 208, identifier:idx; 209, call; 209, 210; 209, 213; 210, attribute; 210, 211; 210, 212; 211, identifier:np; 212, identifier:argsort; 213, argument_list; 213, 214; 214, identifier:prmU; 215, comment; 216, comment; 217, elif_clause; 217, 218; 217, 219; 218, identifier:permute_U; 219, block; 219, 220; 220, expression_statement; 220, 221; 221, assignment; 221, 222; 221, 223; 222, identifier:idx; 223, call; 223, 224; 223, 227; 224, attribute; 224, 225; 224, 226; 225, identifier:np; 226, identifier:argsort; 227, argument_list; 227, 228; 228, identifier:prmV; 229, comment; 230, comment; 231, else_clause; 231, 232; 232, block; 232, 233; 233, return_statement; 233, 234; 234, identifier:similarity; 235, comment; 236, expression_statement; 236, 237; 237, assignment; 237, 238; 237, 239; 238, identifier:prmU; 239, list_comprehension; 239, 240; 239, 243; 240, subscript; 240, 241; 240, 242; 241, identifier:prmU; 242, identifier:i; 243, for_in_clause; 243, 244; 243, 245; 244, identifier:i; 245, identifier:idx; 246, expression_statement; 246, 247; 247, assignment; 247, 248; 247, 249; 248, identifier:prmV; 249, list_comprehension; 249, 250; 249, 253; 250, subscript; 250, 251; 250, 252; 251, identifier:prmV; 252, identifier:i; 253, for_in_clause; 253, 254; 253, 255; 254, identifier:i; 255, identifier:idx; 256, comment; 257, if_statement; 257, 258; 257, 259; 258, identifier:permute_U; 259, block; 259, 260; 260, expression_statement; 260, 261; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:U; 264, identifier:permute; 265, argument_list; 265, 266; 266, identifier:prmU; 267, if_statement; 267, 268; 267, 269; 268, identifier:permute_V; 269, block; 269, 270; 270, expression_statement; 270, 271; 271, call; 271, 272; 271, 275; 272, attribute; 272, 273; 272, 274; 273, identifier:V; 274, identifier:permute; 275, argument_list; 275, 276; 276, identifier:prmV; 277, comment; 278, expression_statement; 278, 279; 279, assignment; 279, 280; 279, 281; 280, identifier:flips; 281, call; 281, 282; 281, 285; 282, attribute; 282, 283; 282, 284; 283, identifier:np; 284, identifier:sign; 285, argument_list; 285, 286; 286, list_comprehension; 286, 287; 286, 291; 287, subscript; 287, 288; 287, 289; 287, 290; 288, identifier:F; 289, identifier:prmU; 290, identifier:prmV; 291, for_in_clause; 291, 292; 291, 293; 292, identifier:F; 293, identifier:sim_matrices; 294, expression_statement; 294, 295; 295, augmented_assignment:*=; 295, 296; 295, 299; 296, subscript; 296, 297; 296, 298; 297, identifier:flips; 298, integer:0; 299, call; 299, 300; 299, 303; 300, attribute; 300, 301; 300, 302; 301, identifier:np; 302, identifier:prod; 303, argument_list; 303, 304; 303, 305; 304, identifier:flips; 305, keyword_argument; 305, 306; 305, 307; 306, identifier:axis; 307, integer:0; 308, comment; 309, if_statement; 309, 310; 309, 311; 309, 329; 310, identifier:permute_U; 311, block; 311, 312; 312, for_statement; 312, 313; 312, 316; 312, 320; 313, pattern_list; 313, 314; 313, 315; 314, identifier:i; 315, identifier:f; 316, call; 316, 317; 316, 318; 317, identifier:enumerate; 318, argument_list; 318, 319; 319, identifier:flips; 320, block; 320, 321; 321, expression_statement; 321, 322; 322, augmented_assignment:*=; 322, 323; 322, 328; 323, subscript; 323, 324; 323, 327; 324, attribute; 324, 325; 324, 326; 325, identifier:U; 326, identifier:factors; 327, identifier:i; 328, identifier:f; 329, elif_clause; 329, 330; 329, 331; 330, identifier:permute_V; 331, block; 331, 332; 332, for_statement; 332, 333; 332, 336; 332, 340; 333, pattern_list; 333, 334; 333, 335; 334, identifier:i; 335, identifier:f; 336, call; 336, 337; 336, 338; 337, identifier:enumerate; 338, argument_list; 338, 339; 339, identifier:flips; 340, block; 340, 341; 341, expression_statement; 341, 342; 342, augmented_assignment:*=; 342, 343; 342, 348; 343, subscript; 343, 344; 343, 347; 344, attribute; 344, 345; 344, 346; 345, identifier:V; 346, identifier:factors; 347, identifier:i; 348, identifier:f; 349, comment; 350, return_statement; 350, 351; 351, identifier:similarity
def kruskal_align(U, V, permute_U=False, permute_V=False): """Aligns two KTensors and returns a similarity score. Parameters ---------- U : KTensor First kruskal tensor to align. V : KTensor Second kruskal tensor to align. permute_U : bool If True, modifies 'U' to align the KTensors (default is False). permute_V : bool If True, modifies 'V' to align the KTensors (default is False). Notes ----- If both `permute_U` and `permute_V` are both set to True, then the factors are ordered from most to least similar. If only one is True then the factors on the modified KTensor are re-ordered to match the factors in the un-aligned KTensor. Returns ------- similarity : float Similarity score between zero and one. """ # Compute similarity matrices. unrm = [f / np.linalg.norm(f, axis=0) for f in U.factors] vnrm = [f / np.linalg.norm(f, axis=0) for f in V.factors] sim_matrices = [np.dot(u.T, v) for u, v in zip(unrm, vnrm)] cost = 1 - np.mean(np.abs(sim_matrices), axis=0) # Solve matching problem via Hungarian algorithm. indices = Munkres().compute(cost.copy()) prmU, prmV = zip(*indices) # Compute mean factor similarity given the optimal matching. similarity = np.mean(1 - cost[prmU, prmV]) # If U and V are of different ranks, identify unmatched factors. unmatched_U = list(set(range(U.rank)) - set(prmU)) unmatched_V = list(set(range(V.rank)) - set(prmV)) # If permuting both U and V, order factors from most to least similar. if permute_U and permute_V: idx = np.argsort(cost[prmU, prmV]) # If permute_U is False, then order the factors such that the ordering # for U is unchanged. elif permute_V: idx = np.argsort(prmU) # If permute_V is False, then order the factors such that the ordering # for V is unchanged. elif permute_U: idx = np.argsort(prmV) # If permute_U and permute_V are both False, then we are done and can # simply return the similarity. else: return similarity # Re-order the factor permutations. prmU = [prmU[i] for i in idx] prmV = [prmV[i] for i in idx] # Permute the factors. if permute_U: U.permute(prmU) if permute_V: V.permute(prmV) # Flip the signs of factors. flips = np.sign([F[prmU, prmV] for F in sim_matrices]) flips[0] *= np.prod(flips, axis=0) # always flip an even number of factors if permute_U: for i, f in enumerate(flips): U.factors[i] *= f elif permute_V: for i, f in enumerate(flips): V.factors[i] *= f # Return the similarity score return similarity
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 12; 2, function_name:randn_ktensor; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 9; 4, identifier:shape; 5, identifier:rank; 6, default_parameter; 6, 7; 6, 8; 7, identifier:norm; 8, None; 9, default_parameter; 9, 10; 9, 11; 10, identifier:random_state; 11, None; 12, block; 12, 13; 12, 15; 12, 16; 12, 23; 12, 24; 12, 42; 13, expression_statement; 13, 14; 14, comment; 15, comment; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:rns; 19, call; 19, 20; 19, 21; 20, identifier:_check_random_state; 21, argument_list; 21, 22; 22, identifier:random_state; 23, comment; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:factors; 27, call; 27, 28; 27, 29; 28, identifier:KTensor; 29, argument_list; 29, 30; 30, list_comprehension; 30, 31; 30, 39; 31, call; 31, 32; 31, 35; 32, attribute; 32, 33; 32, 34; 33, identifier:rns; 34, identifier:standard_normal; 35, argument_list; 35, 36; 36, tuple; 36, 37; 36, 38; 37, identifier:i; 38, identifier:rank; 39, for_in_clause; 39, 40; 39, 41; 40, identifier:i; 41, identifier:shape; 42, return_statement; 42, 43; 43, call; 43, 44; 43, 45; 44, identifier:_rescale_tensor; 45, argument_list; 45, 46; 45, 47; 46, identifier:factors; 47, identifier:norm
def randn_ktensor(shape, rank, norm=None, random_state=None): """ Generates a random N-way tensor with rank R, where the entries are drawn from the standard normal distribution. Parameters ---------- shape : tuple shape of the tensor rank : integer rank of the tensor norm : float or None, optional (defaults: None) If not None, the factor matrices are rescaled so that the Frobenius norm of the returned tensor is equal to ``norm``. random_state : integer, RandomState instance or None, optional (default ``None``) If integer, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Returns ------- X : (I_1, ..., I_N) array_like N-way tensor with rank R. Example ------- >>> # Create a rank-2 tensor of dimension 5x5x5: >>> import tensortools as tt >>> X = tt.randn_tensor((5,5,5), rank=2) """ # Check input. rns = _check_random_state(random_state) # Draw low-rank factor matrices with i.i.d. Gaussian elements. factors = KTensor([rns.standard_normal((i, rank)) for i in shape]) return _rescale_tensor(factors, norm)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 13; 2, function_name:fit; 3, parameters; 3, 4; 3, 5; 3, 6; 3, 7; 3, 10; 4, identifier:self; 5, identifier:X; 6, identifier:ranks; 7, default_parameter; 7, 8; 7, 9; 8, identifier:replicates; 9, integer:1; 10, default_parameter; 10, 11; 10, 12; 11, identifier:verbose; 12, True; 13, block; 13, 14; 13, 16; 13, 17; 13, 32; 13, 33; 13, 185; 13, 186; 13, 227; 13, 228; 13, 229; 13, 230; 13, 291; 13, 292; 14, expression_statement; 14, 15; 15, comment; 16, comment; 17, if_statement; 17, 18; 17, 26; 18, not_operator; 18, 19; 19, call; 19, 20; 19, 21; 20, identifier:isinstance; 21, argument_list; 21, 22; 21, 23; 22, identifier:ranks; 23, attribute; 23, 24; 23, 25; 24, identifier:collections; 25, identifier:Iterable; 26, block; 26, 27; 27, expression_statement; 27, 28; 28, assignment; 28, 29; 28, 30; 29, identifier:ranks; 30, tuple; 30, 31; 31, identifier:ranks; 32, comment; 33, for_statement; 33, 34; 33, 35; 33, 36; 33, 37; 34, identifier:r; 35, identifier:ranks; 36, comment; 37, block; 37, 38; 37, 53; 37, 54; 37, 84; 37, 85; 37, 114; 37, 115; 38, if_statement; 38, 39; 38, 44; 39, comparison_operator:not; 39, 40; 39, 41; 40, identifier:r; 41, attribute; 41, 42; 41, 43; 42, identifier:self; 43, identifier:results; 44, block; 44, 45; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 52; 47, subscript; 47, 48; 47, 51; 48, attribute; 48, 49; 48, 50; 49, identifier:self; 50, identifier:results; 51, identifier:r; 52, list:[]; 53, comment; 54, if_statement; 54, 55; 54, 56; 54, 75; 55, identifier:verbose; 56, block; 56, 57; 57, expression_statement; 57, 58; 58, assignment; 58, 59; 58, 60; 59, identifier:itr; 60, call; 60, 61; 60, 62; 61, identifier:trange; 62, argument_list; 62, 63; 62, 64; 62, 72; 63, identifier:replicates; 64, keyword_argument; 64, 65; 64, 66; 65, identifier:desc; 66, call; 66, 67; 66, 70; 67, attribute; 67, 68; 67, 69; 68, string:'Fitting rank-{} models'; 69, identifier:format; 70, argument_list; 70, 71; 71, identifier:r; 72, keyword_argument; 72, 73; 72, 74; 73, identifier:leave; 74, False; 75, else_clause; 75, 76; 76, block; 76, 77; 77, expression_statement; 77, 78; 78, assignment; 78, 79; 78, 80; 79, identifier:itr; 80, call; 80, 81; 80, 82; 81, identifier:range; 82, argument_list; 82, 83; 83, identifier:replicates; 84, comment; 85, for_statement; 85, 86; 85, 87; 85, 88; 86, identifier:i; 87, identifier:itr; 88, block; 88, 89; 88, 103; 89, expression_statement; 89, 90; 90, assignment; 90, 91; 90, 92; 91, identifier:model_fit; 92, call; 92, 93; 92, 96; 93, attribute; 93, 94; 93, 95; 94, identifier:self; 95, identifier:_fit_method; 96, argument_list; 96, 97; 96, 98; 96, 99; 97, identifier:X; 98, identifier:r; 99, dictionary_splat; 99, 100; 100, attribute; 100, 101; 100, 102; 101, identifier:self; 102, identifier:_fit_options; 103, expression_statement; 103, 104; 104, call; 104, 105; 104, 112; 105, attribute; 105, 106; 105, 111; 106, subscript; 106, 107; 106, 110; 107, attribute; 107, 108; 107, 109; 108, identifier:self; 109, identifier:results; 110, identifier:r; 111, identifier:append; 112, argument_list; 112, 113; 113, identifier:model_fit; 114, comment; 115, if_statement; 115, 116; 115, 117; 116, identifier:verbose; 117, block; 117, 118; 117, 135; 117, 152; 117, 169; 118, expression_statement; 118, 119; 119, assignment; 119, 120; 119, 121; 120, identifier:min_obj; 121, call; 121, 122; 121, 123; 122, identifier:min; 123, argument_list; 123, 124; 124, list_comprehension; 124, 125; 124, 128; 125, attribute; 125, 126; 125, 127; 126, identifier:res; 127, identifier:obj; 128, for_in_clause; 128, 129; 128, 130; 129, identifier:res; 130, subscript; 130, 131; 130, 134; 131, attribute; 131, 132; 131, 133; 132, identifier:self; 133, identifier:results; 134, identifier:r; 135, expression_statement; 135, 136; 136, assignment; 136, 137; 136, 138; 137, identifier:max_obj; 138, call; 138, 139; 138, 140; 139, identifier:max; 140, argument_list; 140, 141; 141, list_comprehension; 141, 142; 141, 145; 142, attribute; 142, 143; 142, 144; 143, identifier:res; 144, identifier:obj; 145, for_in_clause; 145, 146; 145, 147; 146, identifier:res; 147, subscript; 147, 148; 147, 151; 148, attribute; 148, 149; 148, 150; 149, identifier:self; 150, identifier:results; 151, identifier:r; 152, expression_statement; 152, 153; 153, assignment; 153, 154; 153, 155; 154, identifier:elapsed; 155, call; 155, 156; 155, 157; 156, identifier:sum; 157, argument_list; 157, 158; 158, list_comprehension; 158, 159; 158, 162; 159, attribute; 159, 160; 159, 161; 160, identifier:res; 161, identifier:total_time; 162, for_in_clause; 162, 163; 162, 164; 163, identifier:res; 164, subscript; 164, 165; 164, 168; 165, attribute; 165, 166; 165, 167; 166, identifier:self; 167, identifier:results; 168, identifier:r; 169, expression_statement; 169, 170; 170, call; 170, 171; 170, 172; 171, identifier:print; 172, argument_list; 172, 173; 173, call; 173, 174; 173, 180; 174, attribute; 174, 175; 174, 179; 175, concatenated_string; 175, 176; 175, 177; 175, 178; 176, string:'Rank-{} models: min obj, {:.2f}; '; 177, string:'max obj, {:.2f}; time to fit, '; 178, string:'{:.1f}s'; 179, identifier:format; 180, argument_list; 180, 181; 180, 182; 180, 183; 180, 184; 181, identifier:r; 182, identifier:min_obj; 183, identifier:max_obj; 184, identifier:elapsed; 185, comment; 186, for_statement; 186, 187; 186, 188; 186, 189; 187, identifier:r; 188, identifier:ranks; 189, block; 189, 190; 189, 209; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 193; 192, identifier:idx; 193, call; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:np; 196, identifier:argsort; 197, argument_list; 197, 198; 198, list_comprehension; 198, 199; 198, 202; 199, attribute; 199, 200; 199, 201; 200, identifier:result; 201, identifier:obj; 202, for_in_clause; 202, 203; 202, 204; 203, identifier:result; 204, subscript; 204, 205; 204, 208; 205, attribute; 205, 206; 205, 207; 206, identifier:self; 207, identifier:results; 208, identifier:r; 209, expression_statement; 209, 210; 210, assignment; 210, 211; 210, 216; 211, subscript; 211, 212; 211, 215; 212, attribute; 212, 213; 212, 214; 213, identifier:self; 214, identifier:results; 215, identifier:r; 216, list_comprehension; 216, 217; 216, 224; 217, subscript; 217, 218; 217, 223; 218, subscript; 218, 219; 218, 222; 219, attribute; 219, 220; 219, 221; 220, identifier:self; 221, identifier:results; 222, identifier:r; 223, identifier:i; 224, for_in_clause; 224, 225; 224, 226; 225, identifier:i; 226, identifier:idx; 227, comment; 228, comment; 229, comment; 230, for_statement; 230, 231; 230, 232; 230, 243; 231, identifier:i; 232, call; 232, 233; 232, 234; 233, identifier:reversed; 234, argument_list; 234, 235; 235, call; 235, 236; 235, 237; 236, identifier:range; 237, argument_list; 237, 238; 237, 239; 238, integer:1; 239, call; 239, 240; 239, 241; 240, identifier:len; 241, argument_list; 241, 242; 242, identifier:ranks; 243, block; 243, 244; 243, 258; 243, 270; 243, 282; 244, expression_statement; 244, 245; 245, assignment; 245, 246; 245, 249; 246, pattern_list; 246, 247; 246, 248; 247, identifier:r0; 248, identifier:r1; 249, expression_list; 249, 250; 249, 255; 250, subscript; 250, 251; 250, 252; 251, identifier:ranks; 252, binary_operator:-; 252, 253; 252, 254; 253, identifier:i; 254, integer:1; 255, subscript; 255, 256; 255, 257; 256, identifier:ranks; 257, identifier:i; 258, expression_statement; 258, 259; 259, assignment; 259, 260; 259, 261; 260, identifier:U; 261, attribute; 261, 262; 261, 269; 262, subscript; 262, 263; 262, 268; 263, subscript; 263, 264; 263, 267; 264, attribute; 264, 265; 264, 266; 265, identifier:self; 266, identifier:results; 267, identifier:r0; 268, integer:0; 269, identifier:factors; 270, expression_statement; 270, 271; 271, assignment; 271, 272; 271, 273; 272, identifier:V; 273, attribute; 273, 274; 273, 281; 274, subscript; 274, 275; 274, 280; 275, subscript; 275, 276; 275, 279; 276, attribute; 276, 277; 276, 278; 277, identifier:self; 278, identifier:results; 279, identifier:r1; 280, integer:0; 281, identifier:factors; 282, expression_statement; 282, 283; 283, call; 283, 284; 283, 285; 284, identifier:kruskal_align; 285, argument_list; 285, 286; 285, 287; 285, 288; 286, identifier:U; 287, identifier:V; 288, keyword_argument; 288, 289; 288, 290; 289, identifier:permute_U; 290, True; 291, comment; 292, for_statement; 292, 293; 292, 294; 292, 295; 292, 296; 293, identifier:r; 294, identifier:ranks; 295, comment; 296, block; 296, 297; 296, 309; 296, 310; 296, 322; 296, 323; 296, 324; 297, expression_statement; 297, 298; 298, assignment; 298, 299; 298, 300; 299, identifier:U; 300, attribute; 300, 301; 300, 308; 301, subscript; 301, 302; 301, 307; 302, subscript; 302, 303; 302, 306; 303, attribute; 303, 304; 303, 305; 304, identifier:self; 305, identifier:results; 306, identifier:r; 307, integer:0; 308, identifier:factors; 309, comment; 310, expression_statement; 310, 311; 311, assignment; 311, 312; 311, 321; 312, attribute; 312, 313; 312, 320; 313, subscript; 313, 314; 313, 319; 314, subscript; 314, 315; 314, 318; 315, attribute; 315, 316; 315, 317; 316, identifier:self; 317, identifier:results; 318, identifier:r; 319, integer:0; 320, identifier:similarity; 321, float:1.0; 322, comment; 323, comment; 324, for_statement; 324, 325; 324, 326; 324, 335; 325, identifier:res; 326, subscript; 326, 327; 326, 332; 327, subscript; 327, 328; 327, 331; 328, attribute; 328, 329; 328, 330; 329, identifier:self; 330, identifier:results; 331, identifier:r; 332, slice; 332, 333; 332, 334; 333, integer:1; 334, colon; 335, block; 335, 336; 336, expression_statement; 336, 337; 337, assignment; 337, 338; 337, 341; 338, attribute; 338, 339; 338, 340; 339, identifier:res; 340, identifier:similarity; 341, call; 341, 342; 341, 343; 342, identifier:kruskal_align; 343, argument_list; 343, 344; 343, 345; 343, 348; 344, identifier:U; 345, attribute; 345, 346; 345, 347; 346, identifier:res; 347, identifier:factors; 348, keyword_argument; 348, 349; 348, 350; 349, identifier:permute_V; 350, True
def fit(self, X, ranks, replicates=1, verbose=True): """ Fits CP tensor decompositions for different choices of rank. Parameters ---------- X : array_like Real tensor ranks : int, or iterable iterable specifying number of components in each model replicates: int number of models to fit at each rank verbose : bool If True, prints summaries and optimization progress. """ # Make ranks iterable if necessary. if not isinstance(ranks, collections.Iterable): ranks = (ranks,) # Iterate over model ranks, optimize multiple replicates at each rank. for r in ranks: # Initialize storage if r not in self.results: self.results[r] = [] # Display fitting progress. if verbose: itr = trange(replicates, desc='Fitting rank-{} models'.format(r), leave=False) else: itr = range(replicates) # Fit replicates. for i in itr: model_fit = self._fit_method(X, r, **self._fit_options) self.results[r].append(model_fit) # Print summary of results. if verbose: min_obj = min([res.obj for res in self.results[r]]) max_obj = max([res.obj for res in self.results[r]]) elapsed = sum([res.total_time for res in self.results[r]]) print('Rank-{} models: min obj, {:.2f}; ' 'max obj, {:.2f}; time to fit, ' '{:.1f}s'.format(r, min_obj, max_obj, elapsed)) # Sort results from lowest to largest loss. for r in ranks: idx = np.argsort([result.obj for result in self.results[r]]) self.results[r] = [self.results[r][i] for i in idx] # Align best model within each rank to best model of next larger rank. # Here r0 is the rank of the lower-dimensional model and r1 is the rank # of the high-dimensional model. for i in reversed(range(1, len(ranks))): r0, r1 = ranks[i-1], ranks[i] U = self.results[r0][0].factors V = self.results[r1][0].factors kruskal_align(U, V, permute_U=True) # For each rank, align everything to the best model for r in ranks: # store best factors U = self.results[r][0].factors # best model factors self.results[r][0].similarity = 1.0 # similarity to itself # align lesser fit models to best models for res in self.results[r][1:]: res.similarity = kruskal_align(U, res.factors, permute_V=True)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 6; 2, function_name:_create_model_class; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, identifier:model; 6, block; 6, 7; 6, 9; 6, 19; 6, 20; 6, 45; 6, 46; 6, 64; 6, 76; 6, 115; 6, 116; 6, 117; 6, 161; 7, expression_statement; 7, 8; 8, comment; 9, expression_statement; 9, 10; 10, assignment; 10, 11; 10, 12; 11, identifier:cls_name; 12, call; 12, 13; 12, 16; 13, attribute; 13, 14; 13, 15; 14, identifier:model; 15, identifier:replace; 16, argument_list; 16, 17; 16, 18; 17, string:'.'; 18, string:'_'; 19, comment; 20, if_statement; 20, 21; 20, 28; 21, comparison_operator:<; 21, 22; 21, 27; 22, subscript; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:sys; 25, identifier:version_info; 26, integer:0; 27, integer:3; 28, block; 28, 29; 29, if_statement; 29, 30; 29, 35; 30, call; 30, 31; 30, 32; 31, identifier:isinstance; 32, argument_list; 32, 33; 32, 34; 33, identifier:cls_name; 34, identifier:unicode; 35, block; 35, 36; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:cls_name; 39, call; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:cls_name; 42, identifier:encode; 43, argument_list; 43, 44; 44, string:'utf-8'; 45, comment; 46, expression_statement; 46, 47; 47, assignment; 47, 48; 47, 49; 48, identifier:attrs; 49, dictionary; 49, 50; 49, 53; 49, 58; 49, 61; 50, pair; 50, 51; 50, 52; 51, string:'_env'; 52, identifier:self; 53, pair; 53, 54; 53, 55; 54, string:'_odoo'; 55, attribute; 55, 56; 55, 57; 56, identifier:self; 57, identifier:_odoo; 58, pair; 58, 59; 58, 60; 59, string:'_name'; 60, identifier:model; 61, pair; 61, 62; 61, 63; 62, string:'_columns'; 63, dictionary; 64, expression_statement; 64, 65; 65, assignment; 65, 66; 65, 67; 66, identifier:fields_get; 67, call; 67, 68; 67, 73; 68, attribute; 68, 69; 68, 72; 69, attribute; 69, 70; 69, 71; 70, identifier:self; 71, identifier:_odoo; 72, identifier:execute; 73, argument_list; 73, 74; 73, 75; 74, identifier:model; 75, string:'fields_get'; 76, for_statement; 76, 77; 76, 80; 76, 85; 77, pattern_list; 77, 78; 77, 79; 78, identifier:field_name; 79, identifier:field_data; 80, call; 80, 81; 80, 84; 81, attribute; 81, 82; 81, 83; 82, identifier:fields_get; 83, identifier:items; 84, argument_list; 85, block; 85, 86; 86, if_statement; 86, 87; 86, 90; 87, comparison_operator:not; 87, 88; 87, 89; 88, identifier:field_name; 89, identifier:FIELDS_RESERVED; 90, block; 90, 91; 90, 101; 90, 109; 91, expression_statement; 91, 92; 92, assignment; 92, 93; 92, 94; 93, identifier:Field; 94, call; 94, 95; 94, 98; 95, attribute; 95, 96; 95, 97; 96, identifier:fields; 97, identifier:generate_field; 98, argument_list; 98, 99; 98, 100; 99, identifier:field_name; 100, identifier:field_data; 101, expression_statement; 101, 102; 102, assignment; 102, 103; 102, 108; 103, subscript; 103, 104; 103, 107; 104, subscript; 104, 105; 104, 106; 105, identifier:attrs; 106, string:'_columns'; 107, identifier:field_name; 108, identifier:Field; 109, expression_statement; 109, 110; 110, assignment; 110, 111; 110, 114; 111, subscript; 111, 112; 111, 113; 112, identifier:attrs; 113, identifier:field_name; 114, identifier:Field; 115, comment; 116, comment; 117, if_statement; 117, 118; 117, 123; 118, comparison_operator:not; 118, 119; 118, 120; 119, string:'name'; 120, subscript; 120, 121; 120, 122; 121, identifier:attrs; 122, string:'_columns'; 123, block; 123, 124; 123, 137; 123, 147; 123, 155; 124, expression_statement; 124, 125; 125, assignment; 125, 126; 125, 127; 126, identifier:field_data; 127, dictionary; 127, 128; 127, 131; 127, 134; 128, pair; 128, 129; 128, 130; 129, string:'type'; 130, string:'text'; 131, pair; 131, 132; 131, 133; 132, string:'string'; 133, string:'Name'; 134, pair; 134, 135; 134, 136; 135, string:'readonly'; 136, True; 137, expression_statement; 137, 138; 138, assignment; 138, 139; 138, 140; 139, identifier:Field; 140, call; 140, 141; 140, 144; 141, attribute; 141, 142; 141, 143; 142, identifier:fields; 143, identifier:generate_field; 144, argument_list; 144, 145; 144, 146; 145, string:'name'; 146, identifier:field_data; 147, expression_statement; 147, 148; 148, assignment; 148, 149; 148, 154; 149, subscript; 149, 150; 149, 153; 150, subscript; 150, 151; 150, 152; 151, identifier:attrs; 152, string:'_columns'; 153, string:'name'; 154, identifier:Field; 155, expression_statement; 155, 156; 156, assignment; 156, 157; 156, 160; 157, subscript; 157, 158; 157, 159; 158, identifier:attrs; 159, string:'name'; 160, identifier:Field; 161, return_statement; 161, 162; 162, call; 162, 163; 162, 164; 163, identifier:type; 164, argument_list; 164, 165; 164, 166; 164, 168; 165, identifier:cls_name; 166, tuple; 166, 167; 167, identifier:Model; 168, identifier:attrs
def _create_model_class(self, model): """Generate the model proxy class. :return: a :class:`odoorpc.models.Model` class """ cls_name = model.replace('.', '_') # Hack for Python 2 (no need to do this for Python 3) if sys.version_info[0] < 3: if isinstance(cls_name, unicode): cls_name = cls_name.encode('utf-8') # Retrieve server fields info and generate corresponding local fields attrs = { '_env': self, '_odoo': self._odoo, '_name': model, '_columns': {}, } fields_get = self._odoo.execute(model, 'fields_get') for field_name, field_data in fields_get.items(): if field_name not in FIELDS_RESERVED: Field = fields.generate_field(field_name, field_data) attrs['_columns'][field_name] = Field attrs[field_name] = Field # Case where no field 'name' exists, we generate one (which will be # in readonly mode) in purpose to be filled with the 'name_get' method if 'name' not in attrs['_columns']: field_data = {'type': 'text', 'string': 'Name', 'readonly': True} Field = fields.generate_field('name', field_data) attrs['_columns']['name'] = Field attrs['name'] = Field return type(cls_name, (Model,), attrs)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 8; 2, function_name:_init_values; 3, parameters; 3, 4; 3, 5; 4, identifier:self; 5, default_parameter; 5, 6; 5, 7; 6, identifier:context; 7, None; 8, block; 8, 9; 8, 11; 8, 24; 8, 25; 8, 29; 8, 59; 8, 60; 9, expression_statement; 9, 10; 10, comment; 11, if_statement; 11, 12; 11, 15; 12, comparison_operator:is; 12, 13; 12, 14; 13, identifier:context; 14, None; 15, block; 15, 16; 16, expression_statement; 16, 17; 17, assignment; 17, 18; 17, 19; 18, identifier:context; 19, attribute; 19, 20; 19, 23; 20, attribute; 20, 21; 20, 22; 21, identifier:self; 22, identifier:env; 23, identifier:context; 24, comment; 25, expression_statement; 25, 26; 26, assignment; 26, 27; 26, 28; 27, identifier:basic_fields; 28, list:[]; 29, for_statement; 29, 30; 29, 31; 29, 34; 30, identifier:field_name; 31, attribute; 31, 32; 31, 33; 32, identifier:self; 33, identifier:_columns; 34, block; 34, 35; 34, 43; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:field; 38, subscript; 38, 39; 38, 42; 39, attribute; 39, 40; 39, 41; 40, identifier:self; 41, identifier:_columns; 42, identifier:field_name; 43, if_statement; 43, 44; 43, 51; 44, not_operator; 44, 45; 45, call; 45, 46; 45, 47; 46, identifier:getattr; 47, argument_list; 47, 48; 47, 49; 47, 50; 48, identifier:field; 49, string:'relation'; 50, False; 51, block; 51, 52; 52, expression_statement; 52, 53; 53, call; 53, 54; 53, 57; 54, attribute; 54, 55; 54, 56; 55, identifier:basic_fields; 56, identifier:append; 57, argument_list; 57, 58; 58, identifier:field_name; 59, comment; 60, if_statement; 60, 61; 60, 64; 60, 162; 60, 163; 61, attribute; 61, 62; 61, 63; 62, identifier:self; 63, identifier:ids; 64, block; 64, 65; 64, 85; 64, 91; 64, 128; 64, 139; 65, expression_statement; 65, 66; 66, assignment; 66, 67; 66, 68; 67, identifier:rows; 68, call; 68, 69; 68, 74; 69, attribute; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:self; 72, identifier:__class__; 73, identifier:read; 74, argument_list; 74, 75; 74, 78; 74, 79; 74, 82; 75, attribute; 75, 76; 75, 77; 76, identifier:self; 77, identifier:ids; 78, identifier:basic_fields; 79, keyword_argument; 79, 80; 79, 81; 80, identifier:context; 81, identifier:context; 82, keyword_argument; 82, 83; 82, 84; 83, identifier:load; 84, string:'_classic_write'; 85, expression_statement; 85, 86; 86, assignment; 86, 87; 86, 88; 87, identifier:ids_fetched; 88, call; 88, 89; 88, 90; 89, identifier:set; 90, argument_list; 91, for_statement; 91, 92; 91, 93; 91, 94; 92, identifier:row; 93, identifier:rows; 94, block; 94, 95; 94, 104; 95, expression_statement; 95, 96; 96, call; 96, 97; 96, 100; 97, attribute; 97, 98; 97, 99; 98, identifier:ids_fetched; 99, identifier:add; 100, argument_list; 100, 101; 101, subscript; 101, 102; 101, 103; 102, identifier:row; 103, string:'id'; 104, for_statement; 104, 105; 104, 106; 104, 107; 105, identifier:field_name; 106, identifier:row; 107, block; 107, 108; 107, 114; 108, if_statement; 108, 109; 108, 112; 109, comparison_operator:==; 109, 110; 109, 111; 110, identifier:field_name; 111, string:'id'; 112, block; 112, 113; 113, continue_statement; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 125; 116, subscript; 116, 117; 116, 122; 117, subscript; 117, 118; 117, 121; 118, attribute; 118, 119; 118, 120; 119, identifier:self; 120, identifier:_values; 121, identifier:field_name; 122, subscript; 122, 123; 122, 124; 123, identifier:row; 124, string:'id'; 125, subscript; 125, 126; 125, 127; 126, identifier:row; 127, identifier:field_name; 128, expression_statement; 128, 129; 129, assignment; 129, 130; 129, 131; 130, identifier:ids_in_error; 131, binary_operator:-; 131, 132; 131, 138; 132, call; 132, 133; 132, 134; 133, identifier:set; 134, argument_list; 134, 135; 135, attribute; 135, 136; 135, 137; 136, identifier:self; 137, identifier:ids; 138, identifier:ids_fetched; 139, if_statement; 139, 140; 139, 141; 140, identifier:ids_in_error; 141, block; 141, 142; 142, raise_statement; 142, 143; 143, call; 143, 144; 143, 145; 144, identifier:ValueError; 145, argument_list; 145, 146; 146, call; 146, 147; 146, 150; 147, attribute; 147, 148; 147, 149; 148, string:"There is no '{model}' record with IDs {ids}."; 149, identifier:format; 150, argument_list; 150, 151; 150, 156; 151, keyword_argument; 151, 152; 151, 153; 152, identifier:model; 153, attribute; 153, 154; 153, 155; 154, identifier:self; 155, identifier:_name; 156, keyword_argument; 156, 157; 156, 158; 157, identifier:ids; 158, call; 158, 159; 158, 160; 159, identifier:list; 160, argument_list; 160, 161; 161, identifier:ids_in_error; 162, comment; 163, else_clause; 163, 164; 164, block; 164, 165; 164, 184; 165, expression_statement; 165, 166; 166, assignment; 166, 167; 166, 168; 167, identifier:default_get; 168, call; 168, 169; 168, 174; 169, attribute; 169, 170; 169, 173; 170, attribute; 170, 171; 170, 172; 171, identifier:self; 172, identifier:__class__; 173, identifier:default_get; 174, argument_list; 174, 175; 174, 181; 175, call; 175, 176; 175, 177; 176, identifier:list; 177, argument_list; 177, 178; 178, attribute; 178, 179; 178, 180; 179, identifier:self; 180, identifier:_columns; 181, keyword_argument; 181, 182; 181, 183; 182, identifier:context; 183, identifier:context; 184, for_statement; 184, 185; 184, 186; 184, 189; 185, identifier:field_name; 186, attribute; 186, 187; 186, 188; 187, identifier:self; 188, identifier:_columns; 189, block; 189, 190; 190, expression_statement; 190, 191; 191, assignment; 191, 192; 191, 199; 192, subscript; 192, 193; 192, 198; 193, subscript; 193, 194; 193, 197; 194, attribute; 194, 195; 194, 196; 195, identifier:self; 196, identifier:_values; 197, identifier:field_name; 198, None; 199, call; 199, 200; 199, 203; 200, attribute; 200, 201; 200, 202; 201, identifier:default_get; 202, identifier:get; 203, argument_list; 203, 204; 203, 205; 204, identifier:field_name; 205, False
def _init_values(self, context=None): """Retrieve field values from the server. May be used to restore the original values in the purpose to cancel all changes made. """ if context is None: context = self.env.context # Get basic fields (no relational ones) basic_fields = [] for field_name in self._columns: field = self._columns[field_name] if not getattr(field, 'relation', False): basic_fields.append(field_name) # Fetch values from the server if self.ids: rows = self.__class__.read( self.ids, basic_fields, context=context, load='_classic_write') ids_fetched = set() for row in rows: ids_fetched.add(row['id']) for field_name in row: if field_name == 'id': continue self._values[field_name][row['id']] = row[field_name] ids_in_error = set(self.ids) - ids_fetched if ids_in_error: raise ValueError( "There is no '{model}' record with IDs {ids}.".format( model=self._name, ids=list(ids_in_error))) # No ID: fields filled with default values else: default_get = self.__class__.default_get( list(self._columns), context=context) for field_name in self._columns: self._values[field_name][None] = default_get.get( field_name, False)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 5; 2, function_name:parse_resource_id; 3, parameters; 3, 4; 4, identifier:rid; 5, block; 5, 6; 5, 8; 5, 14; 5, 23; 5, 123; 6, expression_statement; 6, 7; 7, comment; 8, if_statement; 8, 9; 8, 11; 9, not_operator; 9, 10; 10, identifier:rid; 11, block; 11, 12; 12, return_statement; 12, 13; 13, dictionary; 14, expression_statement; 14, 15; 15, assignment; 15, 16; 15, 17; 16, identifier:match; 17, call; 17, 18; 17, 21; 18, attribute; 18, 19; 18, 20; 19, identifier:_ARMID_RE; 20, identifier:match; 21, argument_list; 21, 22; 22, identifier:rid; 23, if_statement; 23, 24; 23, 25; 23, 112; 24, identifier:match; 25, block; 25, 26; 25, 34; 25, 47; 25, 51; 25, 90; 25, 105; 26, expression_statement; 26, 27; 27, assignment; 27, 28; 27, 29; 28, identifier:result; 29, call; 29, 30; 29, 33; 30, attribute; 30, 31; 30, 32; 31, identifier:match; 32, identifier:groupdict; 33, argument_list; 34, expression_statement; 34, 35; 35, assignment; 35, 36; 35, 37; 36, identifier:children; 37, call; 37, 38; 37, 41; 38, attribute; 38, 39; 38, 40; 39, identifier:_CHILDREN_RE; 40, identifier:finditer; 41, argument_list; 41, 42; 42, boolean_operator:or; 42, 43; 42, 46; 43, subscript; 43, 44; 43, 45; 44, identifier:result; 45, string:'children'; 46, string:''; 47, expression_statement; 47, 48; 48, assignment; 48, 49; 48, 50; 49, identifier:count; 50, None; 51, for_statement; 51, 52; 51, 55; 51, 59; 52, pattern_list; 52, 53; 52, 54; 53, identifier:count; 54, identifier:child; 55, call; 55, 56; 55, 57; 56, identifier:enumerate; 57, argument_list; 57, 58; 58, identifier:children; 59, block; 59, 60; 60, expression_statement; 60, 61; 61, call; 61, 62; 61, 65; 62, attribute; 62, 63; 62, 64; 63, identifier:result; 64, identifier:update; 65, argument_list; 65, 66; 66, dictionary_comprehension; 66, 67; 66, 77; 67, pair; 67, 68; 67, 76; 68, binary_operator:+; 68, 69; 68, 70; 69, identifier:key; 70, binary_operator:%; 70, 71; 70, 72; 71, string:'_%d'; 72, parenthesized_expression; 72, 73; 73, binary_operator:+; 73, 74; 73, 75; 74, identifier:count; 75, integer:1; 76, identifier:group; 77, for_in_clause; 77, 78; 77, 81; 78, pattern_list; 78, 79; 78, 80; 79, identifier:key; 80, identifier:group; 81, call; 81, 82; 81, 89; 82, attribute; 82, 83; 82, 88; 83, call; 83, 84; 83, 87; 84, attribute; 84, 85; 84, 86; 85, identifier:child; 86, identifier:groupdict; 87, argument_list; 88, identifier:items; 89, argument_list; 90, expression_statement; 90, 91; 91, assignment; 91, 92; 91, 95; 92, subscript; 92, 93; 92, 94; 93, identifier:result; 94, string:'last_child_num'; 95, conditional_expression:if; 95, 96; 95, 99; 95, 104; 96, binary_operator:+; 96, 97; 96, 98; 97, identifier:count; 98, integer:1; 99, call; 99, 100; 99, 101; 100, identifier:isinstance; 101, argument_list; 101, 102; 101, 103; 102, identifier:count; 103, identifier:int; 104, None; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 108; 107, identifier:result; 108, call; 108, 109; 108, 110; 109, identifier:_populate_alternate_kwargs; 110, argument_list; 110, 111; 111, identifier:result; 112, else_clause; 112, 113; 113, block; 113, 114; 114, expression_statement; 114, 115; 115, assignment; 115, 116; 115, 117; 116, identifier:result; 117, call; 117, 118; 117, 119; 118, identifier:dict; 119, argument_list; 119, 120; 120, keyword_argument; 120, 121; 120, 122; 121, identifier:name; 122, identifier:rid; 123, return_statement; 123, 124; 124, dictionary_comprehension; 124, 125; 124, 128; 124, 137; 125, pair; 125, 126; 125, 127; 126, identifier:key; 127, identifier:value; 128, for_in_clause; 128, 129; 128, 132; 129, pattern_list; 129, 130; 129, 131; 130, identifier:key; 131, identifier:value; 132, call; 132, 133; 132, 136; 133, attribute; 133, 134; 133, 135; 134, identifier:result; 135, identifier:items; 136, argument_list; 137, if_clause; 137, 138; 138, comparison_operator:is; 138, 139; 138, 140; 139, identifier:value; 140, None
def parse_resource_id(rid): """Parses a resource_id into its various parts. Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id. :param rid: The resource id being parsed :type rid: str :returns: A dictionary with with following key/value pairs (if found): - subscription: Subscription id - resource_group: Name of resource group - namespace: Namespace for the resource provider (i.e. Microsoft.Compute) - type: Type of the root resource (i.e. virtualMachines) - name: Name of the root resource - child_namespace_{level}: Namespace for the child resoure of that level - child_type_{level}: Type of the child resource of that level - child_name_{level}: Name of the child resource of that level - last_child_num: Level of the last child - resource_parent: Computed parent in the following pattern: providers/{namespace}\ /{parent}/{type}/{name} - resource_namespace: Same as namespace. Note that this may be different than the \ target resource's namespace. - resource_type: Type of the target resource (not the parent) - resource_name: Name of the target resource (not the parent) :rtype: dict[str,str] """ if not rid: return {} match = _ARMID_RE.match(rid) if match: result = match.groupdict() children = _CHILDREN_RE.finditer(result['children'] or '') count = None for count, child in enumerate(children): result.update({ key + '_%d' % (count + 1): group for key, group in child.groupdict().items()}) result['last_child_num'] = count + 1 if isinstance(count, int) else None result = _populate_alternate_kwargs(result) else: result = dict(name=rid) return {key: value for key, value in result.items() if value is not None}
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 26; 2, function_name:lookup_instance; 3, parameters; 3, 4; 3, 8; 3, 13; 3, 18; 4, typed_parameter; 4, 5; 4, 6; 5, identifier:name; 6, type; 6, 7; 7, identifier:str; 8, typed_default_parameter; 8, 9; 8, 10; 8, 12; 9, identifier:instance_type; 10, type; 10, 11; 11, identifier:str; 12, string:''; 13, typed_default_parameter; 13, 14; 13, 15; 13, 17; 14, identifier:image_name; 15, type; 15, 16; 16, identifier:str; 17, string:''; 18, typed_default_parameter; 18, 19; 18, 20; 18, 22; 19, identifier:states; 20, type; 20, 21; 21, identifier:tuple; 22, tuple; 22, 23; 22, 24; 22, 25; 23, string:'running'; 24, string:'stopped'; 25, string:'initializing'; 26, block; 26, 27; 26, 29; 26, 35; 26, 55; 26, 61; 26, 67; 26, 68; 26, 69; 26, 73; 27, expression_statement; 27, 28; 28, comment; 29, expression_statement; 29, 30; 30, assignment; 30, 31; 30, 32; 31, identifier:ec2; 32, call; 32, 33; 32, 34; 33, identifier:get_ec2_resource; 34, argument_list; 35, expression_statement; 35, 36; 36, assignment; 36, 37; 36, 38; 37, identifier:instances; 38, call; 38, 39; 38, 44; 39, attribute; 39, 40; 39, 43; 40, attribute; 40, 41; 40, 42; 41, identifier:ec2; 42, identifier:instances; 43, identifier:filter; 44, argument_list; 44, 45; 45, keyword_argument; 45, 46; 45, 47; 46, identifier:Filters; 47, list:[{'Name': 'instance-state-name', 'Values': states}]; 47, 48; 48, dictionary; 48, 49; 48, 52; 49, pair; 49, 50; 49, 51; 50, string:'Name'; 51, string:'instance-state-name'; 52, pair; 52, 53; 52, 54; 53, string:'Values'; 54, identifier:states; 55, expression_statement; 55, 56; 56, assignment; 56, 57; 56, 58; 57, identifier:prefix; 58, call; 58, 59; 58, 60; 59, identifier:get_prefix; 60, argument_list; 61, expression_statement; 61, 62; 62, assignment; 62, 63; 62, 64; 63, identifier:username; 64, call; 64, 65; 64, 66; 65, identifier:get_username; 66, argument_list; 67, comment; 68, comment; 69, expression_statement; 69, 70; 70, assignment; 70, 71; 70, 72; 71, identifier:result; 72, list:[]; 73, for_statement; 73, 74; 73, 75; 73, 80; 74, identifier:i; 75, call; 75, 76; 75, 79; 76, attribute; 76, 77; 76, 78; 77, identifier:instances; 78, identifier:all; 79, argument_list; 80, block; 80, 81; 80, 88; 80, 94; 80, 105; 80, 116; 80, 127; 80, 137; 80, 149; 80, 156; 80, 164; 81, expression_statement; 81, 82; 82, assignment; 82, 83; 82, 84; 83, identifier:instance_name; 84, call; 84, 85; 84, 86; 85, identifier:get_name; 86, argument_list; 86, 87; 87, identifier:i; 88, if_statement; 88, 89; 88, 92; 89, comparison_operator:!=; 89, 90; 89, 91; 90, identifier:instance_name; 91, identifier:name; 92, block; 92, 93; 93, continue_statement; 94, expression_statement; 94, 95; 95, assignment; 95, 96; 95, 99; 96, pattern_list; 96, 97; 96, 98; 97, identifier:seen_prefix; 98, identifier:seen_username; 99, call; 99, 100; 99, 101; 100, identifier:parse_key_name; 101, argument_list; 101, 102; 102, attribute; 102, 103; 102, 104; 103, identifier:i; 104, identifier:key_name; 105, if_statement; 105, 106; 105, 109; 106, comparison_operator:!=; 106, 107; 106, 108; 107, identifier:prefix; 108, identifier:seen_prefix; 109, block; 109, 110; 109, 115; 110, expression_statement; 110, 111; 111, call; 111, 112; 111, 113; 112, identifier:print; 113, argument_list; 113, 114; 114, string:f"Found {name} launched under {seen_prefix}, ignoring"; 115, continue_statement; 116, if_statement; 116, 117; 116, 120; 117, comparison_operator:!=; 117, 118; 117, 119; 118, identifier:username; 119, identifier:seen_username; 120, block; 120, 121; 120, 126; 121, expression_statement; 121, 122; 122, call; 122, 123; 122, 124; 123, identifier:print; 124, argument_list; 124, 125; 125, string:f"Found {name} launched by {seen_username}, ignoring"; 126, continue_statement; 127, if_statement; 127, 128; 127, 129; 128, identifier:instance_type; 129, block; 129, 130; 130, assert_statement; 130, 131; 130, 136; 131, comparison_operator:==; 131, 132; 131, 135; 132, attribute; 132, 133; 132, 134; 133, identifier:i; 134, identifier:instance_type; 135, identifier:instance_type; 136, string:f"Found existing instance for job {name} but different instance type ({i.instance_type}) than requested ({instance_type}), terminate {name} first or use new task name."; 137, if_statement; 137, 138; 137, 139; 138, identifier:image_name; 139, block; 139, 140; 140, assert_statement; 140, 141; 140, 148; 141, comparison_operator:==; 141, 142; 141, 147; 142, attribute; 142, 143; 142, 146; 143, attribute; 143, 144; 143, 145; 144, identifier:i; 145, identifier:image; 146, identifier:name; 147, identifier:image_name; 148, string:f"Found existing instance for job {name} but launched with different image ({i.image.name}) than requested ({image_name}), terminate {name} first or use new task name."; 149, expression_statement; 149, 150; 150, call; 150, 151; 150, 154; 151, attribute; 151, 152; 151, 153; 152, identifier:result; 153, identifier:append; 154, argument_list; 154, 155; 155, identifier:i; 156, assert_statement; 156, 157; 156, 163; 157, comparison_operator:<; 157, 158; 157, 162; 158, call; 158, 159; 158, 160; 159, identifier:len; 160, argument_list; 160, 161; 161, identifier:result; 162, integer:2; 163, string:f"Found two instances with name {name}"; 164, if_statement; 164, 165; 164, 167; 164, 170; 165, not_operator; 165, 166; 166, identifier:result; 167, block; 167, 168; 168, return_statement; 168, 169; 169, None; 170, else_clause; 170, 171; 171, block; 171, 172; 172, return_statement; 172, 173; 173, subscript; 173, 174; 173, 175; 174, identifier:result; 175, integer:0
def lookup_instance(name: str, instance_type: str = '', image_name: str = '', states: tuple = ('running', 'stopped', 'initializing')): """Looks up AWS instance for given instance name, like simple.worker. If no instance found in current AWS environment, returns None. """ ec2 = get_ec2_resource() instances = ec2.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': states}]) prefix = get_prefix() username = get_username() # look for an existing instance matching job, ignore instances launched # by different user or under different resource name result = [] for i in instances.all(): instance_name = get_name(i) if instance_name != name: continue seen_prefix, seen_username = parse_key_name(i.key_name) if prefix != seen_prefix: print(f"Found {name} launched under {seen_prefix}, ignoring") continue if username != seen_username: print(f"Found {name} launched by {seen_username}, ignoring") continue if instance_type: assert i.instance_type == instance_type, f"Found existing instance for job {name} but different instance type ({i.instance_type}) than requested ({instance_type}), terminate {name} first or use new task name." if image_name: assert i.image.name == image_name, f"Found existing instance for job {name} but launched with different image ({i.image.name}) than requested ({image_name}), terminate {name} first or use new task name." result.append(i) assert len(result) < 2, f"Found two instances with name {name}" if not result: return None else: return result[0]
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 7; 2, function_name:extract_attr_for_match; 3, parameters; 3, 4; 3, 5; 4, identifier:items; 5, dictionary_splat_pattern; 5, 6; 6, identifier:kwargs; 7, block; 7, 8; 7, 10; 7, 11; 7, 15; 7, 40; 7, 44; 7, 55; 7, 129; 7, 144; 7, 151; 8, expression_statement; 8, 9; 9, comment; 10, comment; 11, expression_statement; 11, 12; 12, assignment; 12, 13; 12, 14; 13, identifier:query_arg; 14, None; 15, for_statement; 15, 16; 15, 19; 15, 24; 16, pattern_list; 16, 17; 16, 18; 17, identifier:arg; 18, identifier:value; 19, call; 19, 20; 19, 23; 20, attribute; 20, 21; 20, 22; 21, identifier:kwargs; 22, identifier:items; 23, argument_list; 24, block; 24, 25; 25, if_statement; 25, 26; 25, 30; 26, comparison_operator:==; 26, 27; 26, 28; 27, identifier:value; 28, unary_operator:-; 28, 29; 29, integer:1; 30, block; 30, 31; 30, 36; 31, assert_statement; 31, 32; 31, 35; 32, comparison_operator:is; 32, 33; 32, 34; 33, identifier:query_arg; 34, None; 35, string:"Only single query arg (-1 valued) is allowed"; 36, expression_statement; 36, 37; 37, assignment; 37, 38; 37, 39; 38, identifier:query_arg; 39, identifier:arg; 40, expression_statement; 40, 41; 41, assignment; 41, 42; 41, 43; 42, identifier:result; 43, list:[]; 44, expression_statement; 44, 45; 45, assignment; 45, 46; 45, 47; 46, identifier:filterset; 47, call; 47, 48; 47, 49; 48, identifier:set; 49, argument_list; 49, 50; 50, call; 50, 51; 50, 54; 51, attribute; 51, 52; 51, 53; 52, identifier:kwargs; 53, identifier:keys; 54, argument_list; 55, for_statement; 55, 56; 55, 57; 55, 58; 56, identifier:item; 57, identifier:items; 58, block; 58, 59; 58, 63; 58, 88; 58, 117; 59, expression_statement; 59, 60; 60, assignment; 60, 61; 60, 62; 61, identifier:match; 62, True; 63, assert_statement; 63, 64; 63, 74; 64, call; 64, 65; 64, 68; 65, attribute; 65, 66; 65, 67; 66, identifier:filterset; 67, identifier:issubset; 68, argument_list; 68, 69; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:item; 72, identifier:keys; 73, argument_list; 74, binary_operator:%; 74, 75; 74, 76; 75, string:"Filter set contained %s which was not in record %s"; 76, tuple; 76, 77; 76, 87; 77, call; 77, 78; 77, 81; 78, attribute; 78, 79; 78, 80; 79, identifier:filterset; 80, identifier:difference; 81, argument_list; 81, 82; 82, call; 82, 83; 82, 86; 83, attribute; 83, 84; 83, 85; 84, identifier:item; 85, identifier:keys; 86, argument_list; 87, identifier:item; 88, for_statement; 88, 89; 88, 90; 88, 91; 89, identifier:arg; 90, identifier:item; 91, block; 91, 92; 91, 98; 92, if_statement; 92, 93; 92, 96; 93, comparison_operator:==; 93, 94; 93, 95; 94, identifier:arg; 95, identifier:query_arg; 96, block; 96, 97; 97, continue_statement; 98, if_statement; 98, 99; 98, 102; 99, comparison_operator:in; 99, 100; 99, 101; 100, identifier:arg; 101, identifier:kwargs; 102, block; 102, 103; 103, if_statement; 103, 104; 103, 111; 104, comparison_operator:!=; 104, 105; 104, 108; 105, subscript; 105, 106; 105, 107; 106, identifier:item; 107, identifier:arg; 108, subscript; 108, 109; 108, 110; 109, identifier:kwargs; 110, identifier:arg; 111, block; 111, 112; 111, 116; 112, expression_statement; 112, 113; 113, assignment; 113, 114; 113, 115; 114, identifier:match; 115, False; 116, break_statement; 117, if_statement; 117, 118; 117, 119; 118, identifier:match; 119, block; 119, 120; 120, expression_statement; 120, 121; 121, call; 121, 122; 121, 125; 122, attribute; 122, 123; 122, 124; 123, identifier:result; 124, identifier:append; 125, argument_list; 125, 126; 126, subscript; 126, 127; 126, 128; 127, identifier:item; 128, identifier:query_arg; 129, assert_statement; 129, 130; 129, 136; 130, comparison_operator:<=; 130, 131; 130, 135; 131, call; 131, 132; 131, 133; 132, identifier:len; 133, argument_list; 133, 134; 134, identifier:result; 135, integer:1; 136, binary_operator:%; 136, 137; 136, 138; 137, string:"%d values matched %s, only allow 1"; 138, tuple; 138, 139; 138, 143; 139, call; 139, 140; 139, 141; 140, identifier:len; 141, argument_list; 141, 142; 142, identifier:result; 143, identifier:kwargs; 144, if_statement; 144, 145; 144, 146; 145, identifier:result; 146, block; 146, 147; 147, return_statement; 147, 148; 148, subscript; 148, 149; 148, 150; 149, identifier:result; 150, integer:0; 151, return_statement; 151, 152; 152, None
def extract_attr_for_match(items, **kwargs): """Helper method to get attribute value for an item matching some criterion. Specify target criteria value as dict, with target attribute having value -1 Example: to extract state of vpc matching given vpc id response = [{'State': 'available', 'VpcId': 'vpc-2bb1584c'}] extract_attr_for_match(response, State=-1, VpcId='vpc-2bb1584c') #=> 'available'""" # find the value of attribute to return query_arg = None for arg, value in kwargs.items(): if value == -1: assert query_arg is None, "Only single query arg (-1 valued) is allowed" query_arg = arg result = [] filterset = set(kwargs.keys()) for item in items: match = True assert filterset.issubset( item.keys()), "Filter set contained %s which was not in record %s" % ( filterset.difference(item.keys()), item) for arg in item: if arg == query_arg: continue if arg in kwargs: if item[arg] != kwargs[arg]: match = False break if match: result.append(item[query_arg]) assert len(result) <= 1, "%d values matched %s, only allow 1" % ( len(result), kwargs) if result: return result[0] return None
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:_maybe_create_resources; 3, parameters; 3, 4; 4, typed_default_parameter; 4, 5; 4, 6; 4, 8; 5, identifier:logging_task; 6, type; 6, 7; 7, identifier:Task; 8, None; 9, block; 9, 10; 9, 12; 9, 39; 9, 122; 10, expression_statement; 10, 11; 11, comment; 12, function_definition; 12, 13; 12, 14; 12, 17; 13, function_name:log; 14, parameters; 14, 15; 15, list_splat_pattern; 15, 16; 16, identifier:args; 17, block; 17, 18; 18, if_statement; 18, 19; 18, 20; 18, 29; 19, identifier:logging_task; 20, block; 20, 21; 21, expression_statement; 21, 22; 22, call; 22, 23; 22, 26; 23, attribute; 23, 24; 23, 25; 24, identifier:logging_task; 25, identifier:log; 26, argument_list; 26, 27; 27, list_splat; 27, 28; 28, identifier:args; 29, else_clause; 29, 30; 30, block; 30, 31; 31, expression_statement; 31, 32; 32, call; 32, 33; 32, 36; 33, attribute; 33, 34; 33, 35; 34, identifier:util; 35, identifier:log; 36, argument_list; 36, 37; 37, list_splat; 37, 38; 38, identifier:args; 39, function_definition; 39, 40; 39, 41; 39, 42; 40, function_name:should_create_resources; 41, parameters; 42, block; 42, 43; 42, 45; 42, 53; 42, 73; 42, 81; 42, 93; 42, 99; 42, 108; 42, 120; 43, expression_statement; 43, 44; 44, comment; 45, expression_statement; 45, 46; 46, assignment; 46, 47; 46, 48; 47, identifier:prefix; 48, call; 48, 49; 48, 52; 49, attribute; 49, 50; 49, 51; 50, identifier:u; 51, identifier:get_prefix; 52, argument_list; 53, if_statement; 53, 54; 53, 65; 54, comparison_operator:not; 54, 55; 54, 60; 55, call; 55, 56; 55, 59; 56, attribute; 56, 57; 56, 58; 57, identifier:u; 58, identifier:get_keypair_name; 59, argument_list; 60, call; 60, 61; 60, 64; 61, attribute; 61, 62; 61, 63; 62, identifier:u; 63, identifier:get_keypair_dict; 64, argument_list; 65, block; 65, 66; 65, 71; 66, expression_statement; 66, 67; 67, call; 67, 68; 67, 69; 68, identifier:log; 69, argument_list; 69, 70; 70, string:f"Missing {u.get_keypair_name()} keypair, creating resources"; 71, return_statement; 71, 72; 72, True; 73, expression_statement; 73, 74; 74, assignment; 74, 75; 74, 76; 75, identifier:vpcs; 76, call; 76, 77; 76, 80; 77, attribute; 77, 78; 77, 79; 78, identifier:u; 79, identifier:get_vpc_dict; 80, argument_list; 81, if_statement; 81, 82; 81, 85; 82, comparison_operator:not; 82, 83; 82, 84; 83, identifier:prefix; 84, identifier:vpcs; 85, block; 85, 86; 85, 91; 86, expression_statement; 86, 87; 87, call; 87, 88; 87, 89; 88, identifier:log; 89, argument_list; 89, 90; 90, string:f"Missing {prefix} vpc, creating resources"; 91, return_statement; 91, 92; 92, True; 93, expression_statement; 93, 94; 94, assignment; 94, 95; 94, 96; 95, identifier:vpc; 96, subscript; 96, 97; 96, 98; 97, identifier:vpcs; 98, identifier:prefix; 99, expression_statement; 99, 100; 100, assignment; 100, 101; 100, 102; 101, identifier:gateways; 102, call; 102, 103; 102, 106; 103, attribute; 103, 104; 103, 105; 104, identifier:u; 105, identifier:get_gateway_dict; 106, argument_list; 106, 107; 107, identifier:vpc; 108, if_statement; 108, 109; 108, 112; 109, comparison_operator:not; 109, 110; 109, 111; 110, identifier:prefix; 111, identifier:gateways; 112, block; 112, 113; 112, 118; 113, expression_statement; 113, 114; 114, call; 114, 115; 114, 116; 115, identifier:log; 116, argument_list; 116, 117; 117, string:f"Missing {prefix} gateway, creating resources"; 118, return_statement; 118, 119; 119, True; 120, return_statement; 120, 121; 121, False; 122, try_statement; 122, 123; 122, 124; 122, 248; 123, comment; 124, block; 124, 125; 124, 202; 124, 221; 124, 242; 125, if_statement; 125, 126; 125, 134; 126, call; 126, 127; 126, 132; 127, attribute; 127, 128; 127, 131; 128, attribute; 128, 129; 128, 130; 129, identifier:os; 130, identifier:path; 131, identifier:exists; 132, argument_list; 132, 133; 133, identifier:AWS_LOCK_FN; 134, block; 134, 135; 134, 154; 134, 161; 134, 170; 134, 201; 135, expression_statement; 135, 136; 136, assignment; 136, 137; 136, 141; 137, pattern_list; 137, 138; 137, 139; 137, 140; 138, identifier:pid; 139, identifier:ts; 140, identifier:lock_taskname; 141, call; 141, 142; 141, 152; 142, attribute; 142, 143; 142, 151; 143, call; 143, 144; 143, 150; 144, attribute; 144, 145; 144, 149; 145, call; 145, 146; 145, 147; 146, identifier:open; 147, argument_list; 147, 148; 148, identifier:AWS_LOCK_FN; 149, identifier:read; 150, argument_list; 151, identifier:split; 152, argument_list; 152, 153; 153, string:'-'; 154, expression_statement; 154, 155; 155, assignment; 155, 156; 155, 157; 156, identifier:ts; 157, call; 157, 158; 157, 159; 158, identifier:int; 159, argument_list; 159, 160; 160, identifier:ts; 161, expression_statement; 161, 162; 162, call; 162, 163; 162, 164; 163, identifier:log; 164, argument_list; 164, 165; 165, concatenated_string; 165, 166; 165, 167; 165, 168; 165, 169; 166, string:f"waiting for aws resource creation, another resource initiation was "; 167, string:f"initiated {int(time.time()-ts)} seconds ago by "; 168, string:f"{lock_taskname}, delete lock file "; 169, string:f"{AWS_LOCK_FN} if this is an error"; 170, while_statement; 170, 171; 170, 172; 171, True; 172, block; 172, 173; 173, if_statement; 173, 174; 173, 182; 173, 198; 174, call; 174, 175; 174, 180; 175, attribute; 175, 176; 175, 179; 176, attribute; 176, 177; 176, 178; 177, identifier:os; 178, identifier:path; 179, identifier:exists; 180, argument_list; 180, 181; 181, identifier:AWS_LOCK_FN; 182, block; 182, 183; 182, 190; 182, 197; 183, expression_statement; 183, 184; 184, call; 184, 185; 184, 186; 185, identifier:log; 186, argument_list; 186, 187; 187, concatenated_string; 187, 188; 187, 189; 188, string:f"waiting for lock file {AWS_LOCK_FN} to get deleted "; 189, string:f"initiated {int(time.time()-ts)} seconds ago by "; 190, expression_statement; 190, 191; 191, call; 191, 192; 191, 195; 192, attribute; 192, 193; 192, 194; 193, identifier:time; 194, identifier:sleep; 195, argument_list; 195, 196; 196, integer:2; 197, continue_statement; 198, else_clause; 198, 199; 199, block; 199, 200; 200, break_statement; 201, return_statement; 202, with_statement; 202, 203; 202, 213; 203, with_clause; 203, 204; 204, with_item; 204, 205; 205, as_pattern; 205, 206; 205, 211; 206, call; 206, 207; 206, 208; 207, identifier:open; 208, argument_list; 208, 209; 208, 210; 209, identifier:AWS_LOCK_FN; 210, string:'w'; 211, as_pattern_target; 211, 212; 212, identifier:f; 213, block; 213, 214; 214, expression_statement; 214, 215; 215, call; 215, 216; 215, 219; 216, attribute; 216, 217; 216, 218; 217, identifier:f; 218, identifier:write; 219, argument_list; 219, 220; 220, string:f'{os.getpid()}-{int(time.time())}-{logging_task.name if logging_task else ""}'; 221, if_statement; 221, 222; 221, 226; 222, not_operator; 222, 223; 223, call; 223, 224; 223, 225; 224, identifier:should_create_resources; 225, argument_list; 226, block; 226, 227; 226, 234; 226, 241; 227, expression_statement; 227, 228; 228, call; 228, 229; 228, 232; 229, attribute; 229, 230; 229, 231; 230, identifier:util; 231, identifier:log; 232, argument_list; 232, 233; 233, string:"Resources already created, no-op"; 234, expression_statement; 234, 235; 235, call; 235, 236; 235, 239; 236, attribute; 236, 237; 236, 238; 237, identifier:os; 238, identifier:remove; 239, argument_list; 239, 240; 240, identifier:AWS_LOCK_FN; 241, return_statement; 242, expression_statement; 242, 243; 243, call; 243, 244; 243, 247; 244, attribute; 244, 245; 244, 246; 245, identifier:create_lib; 246, identifier:create_resources; 247, argument_list; 248, finally_clause; 248, 249; 249, block; 249, 250; 250, if_statement; 250, 251; 250, 259; 251, call; 251, 252; 251, 257; 252, attribute; 252, 253; 252, 256; 253, attribute; 253, 254; 253, 255; 254, identifier:os; 255, identifier:path; 256, identifier:exists; 257, argument_list; 257, 258; 258, identifier:AWS_LOCK_FN; 259, block; 259, 260; 260, expression_statement; 260, 261; 261, call; 261, 262; 261, 265; 262, attribute; 262, 263; 262, 264; 263, identifier:os; 264, identifier:remove; 265, argument_list; 265, 266; 266, identifier:AWS_LOCK_FN
def _maybe_create_resources(logging_task: Task = None): """Use heuristics to decide to possibly create resources""" def log(*args): if logging_task: logging_task.log(*args) else: util.log(*args) def should_create_resources(): """Check if gateway, keypair, vpc exist.""" prefix = u.get_prefix() if u.get_keypair_name() not in u.get_keypair_dict(): log(f"Missing {u.get_keypair_name()} keypair, creating resources") return True vpcs = u.get_vpc_dict() if prefix not in vpcs: log(f"Missing {prefix} vpc, creating resources") return True vpc = vpcs[prefix] gateways = u.get_gateway_dict(vpc) if prefix not in gateways: log(f"Missing {prefix} gateway, creating resources") return True return False try: # this locking is approximate, still possible for threads to slip through if os.path.exists(AWS_LOCK_FN): pid, ts, lock_taskname = open(AWS_LOCK_FN).read().split('-') ts = int(ts) log(f"waiting for aws resource creation, another resource initiation was " f"initiated {int(time.time()-ts)} seconds ago by " f"{lock_taskname}, delete lock file " f"{AWS_LOCK_FN} if this is an error") while True: if os.path.exists(AWS_LOCK_FN): log(f"waiting for lock file {AWS_LOCK_FN} to get deleted " f"initiated {int(time.time()-ts)} seconds ago by ") time.sleep(2) continue else: break return with open(AWS_LOCK_FN, 'w') as f: f.write( f'{os.getpid()}-{int(time.time())}-{logging_task.name if logging_task else ""}') if not should_create_resources(): util.log("Resources already created, no-op") os.remove(AWS_LOCK_FN) return create_lib.create_resources() finally: if os.path.exists(AWS_LOCK_FN): os.remove(AWS_LOCK_FN)
0, module; 0, 1; 1, function_definition; 1, 2; 1, 3; 1, 9; 2, function_name:_set_aws_environment; 3, parameters; 3, 4; 4, typed_default_parameter; 4, 5; 4, 6; 4, 8; 5, identifier:task; 6, type; 6, 7; 7, identifier:Task; 8, None; 9, block; 9, 10; 9, 12; 9, 24; 9, 36; 9, 63; 9, 89; 9, 90; 9, 113; 9, 114; 9, 115; 9, 150; 9, 151; 9, 152; 9, 153; 9, 154; 10, expression_statement; 10, 11; 11, comment; 12, expression_statement; 12, 13; 13, assignment; 13, 14; 13, 15; 14, identifier:current_zone; 15, call; 15, 16; 15, 21; 16, attribute; 16, 17; 16, 20; 17, attribute; 17, 18; 17, 19; 18, identifier:os; 19, identifier:environ; 20, identifier:get; 21, argument_list; 21, 22; 21, 23; 22, string:'NCLUSTER_ZONE'; 23, string:''; 24, expression_statement; 24, 25; 25, assignment; 25, 26; 25, 27; 26, identifier:current_region; 27, call; 27, 28; 27, 33; 28, attribute; 28, 29; 28, 32; 29, attribute; 29, 30; 29, 31; 30, identifier:os; 31, identifier:environ; 32, identifier:get; 33, argument_list; 33, 34; 33, 35; 34, string:'AWS_DEFAULT_REGION'; 35, string:''; 36, function_definition; 36, 37; 36, 38; 36, 41; 37, function_name:log; 38, parameters; 38, 39; 39, list_splat_pattern; 39, 40; 40, identifier:args; 41, block; 41, 42; 42, if_statement; 42, 43; 42, 44; 42, 53; 43, identifier:task; 44, block; 44, 45; 45, expression_statement; 45, 46; 46, call; 46, 47; 46, 50; 47, attribute; 47, 48; 47, 49; 48, identifier:task; 49, identifier:log; 50, argument_list; 50, 51; 51, list_splat; 51, 52; 52, identifier:args; 53, else_clause; 53, 54; 54, block; 54, 55; 55, expression_statement; 55, 56; 56, call; 56, 57; 56, 60; 57, attribute; 57, 58; 57, 59; 58, identifier:util; 59, identifier:log; 60, argument_list; 60, 61; 61, list_splat; 61, 62; 62, identifier:args; 63, if_statement; 63, 64; 63, 67; 64, boolean_operator:and; 64, 65; 64, 66; 65, identifier:current_region; 66, identifier:current_zone; 67, block; 67, 68; 67, 78; 67, 88; 68, assert_statement; 68, 69; 68, 75; 69, call; 69, 70; 69, 73; 70, attribute; 70, 71; 70, 72; 71, identifier:current_zone; 72, identifier:startswith; 73, argument_list; 73, 74; 74, identifier:current_region; 75, concatenated_string; 75, 76; 75, 77; 76, string:f'Current zone "{current_zone}" ($NCLUSTER_ZONE) is not '; 77, string:f'in current region "{current_region} ($AWS_DEFAULT_REGION)'; 78, assert_statement; 78, 79; 79, comparison_operator:==; 79, 80; 79, 87; 80, attribute; 80, 81; 80, 86; 81, call; 81, 82; 81, 85; 82, attribute; 82, 83; 82, 84; 83, identifier:u; 84, identifier:get_session; 85, argument_list; 86, identifier:region_name; 87, identifier:current_region; 88, comment; 89, comment; 90, if_statement; 90, 91; 90, 95; 91, boolean_operator:and; 91, 92; 91, 93; 92, identifier:current_zone; 93, not_operator; 93, 94; 94, identifier:current_region; 95, block; 95, 96; 95, 105; 96, expression_statement; 96, 97; 97, assignment; 97, 98; 97, 99; 98, identifier:current_region; 99, subscript; 99, 100; 99, 101; 100, identifier:current_zone; 101, slice; 101, 102; 101, 103; 102, colon; 103, unary_operator:-; 103, 104; 104, integer:1; 105, expression_statement; 105, 106; 106, assignment; 106, 107; 106, 112; 107, subscript; 107, 108; 107, 111; 108, attribute; 108, 109; 108, 110; 109, identifier:os; 110, identifier:environ; 111, string:'AWS_DEFAULT_REGION'; 112, identifier:current_region; 113, comment; 114, comment; 115, if_statement; 115, 116; 115, 118; 116, not_operator; 116, 117; 117, identifier:current_region; 118, block; 118, 119; 118, 129; 118, 142; 119, expression_statement; 119, 120; 120, assignment; 120, 121; 120, 122; 121, identifier:current_region; 122, attribute; 122, 123; 122, 128; 123, call; 123, 124; 123, 127; 124, attribute; 124, 125; 124, 126; 125, identifier:u; 126, identifier:get_session; 127, argument_list; 128, identifier:region_name; 129, if_statement; 129, 130; 129, 132; 130, not_operator; 130, 131; 131, identifier:current_region; 132, block; 132, 133; 132, 138; 133, expression_statement; 133, 134; 134, call; 134, 135; 134, 136; 135, identifier:log; 136, argument_list; 136, 137; 137, string:f"No default region available, using {NCLUSTER_DEFAULT_REGION}"; 138, expression_statement; 138, 139; 139, assignment; 139, 140; 139, 141; 140, identifier:current_region; 141, identifier:NCLUSTER_DEFAULT_REGION; 142, expression_statement; 142, 143; 143, assignment; 143, 144; 143, 149; 144, subscript; 144, 145; 144, 148; 145, attribute; 145, 146; 145, 147; 146, identifier:os; 147, identifier:environ; 148, string:'AWS_DEFAULT_REGION'; 149, identifier:current_region; 150, comment; 151, comment; 152, comment; 153, comment; 154, expression_statement; 154, 155; 155, call; 155, 156; 155, 157; 156, identifier:log; 157, argument_list; 157, 158; 158, concatenated_string; 158, 159; 158, 160; 159, string:f"Using account {u.get_account_number()}, region {current_region}, "; 160, string:f"zone {current_zone}"
def _set_aws_environment(task: Task = None): """Sets up AWS environment from NCLUSTER environment variables""" current_zone = os.environ.get('NCLUSTER_ZONE', '') current_region = os.environ.get('AWS_DEFAULT_REGION', '') def log(*args): if task: task.log(*args) else: util.log(*args) if current_region and current_zone: assert current_zone.startswith( current_region), f'Current zone "{current_zone}" ($NCLUSTER_ZONE) is not ' \ f'in current region "{current_region} ($AWS_DEFAULT_REGION)' assert u.get_session().region_name == current_region # setting from ~/.aws # zone is set, set region from zone if current_zone and not current_region: current_region = current_zone[:-1] os.environ['AWS_DEFAULT_REGION'] = current_region # neither zone nor region not set, use default setting for region # if default is not set, use NCLUSTER_DEFAULT_REGION if not current_region: current_region = u.get_session().region_name if not current_region: log(f"No default region available, using {NCLUSTER_DEFAULT_REGION}") current_region = NCLUSTER_DEFAULT_REGION os.environ['AWS_DEFAULT_REGION'] = current_region # zone not set, use first zone of the region # if not current_zone: # current_zone = current_region + 'a' # os.environ['NCLUSTER_ZONE'] = current_zone log(f"Using account {u.get_account_number()}, region {current_region}, " f"zone {current_zone}")